Design mode summary

Keywords: C# Programming

  • Through encapsulation, inheritance and polymorphism, the coupling degree of the program is reduced, making the program more flexible, easy to modify and easy to reuse
Simple factory
public class Operation {
        public double NumberA { get; set; }
        public double NumberB { get; set; }
        public virtual double GetResult()
        {
            double result = 0;
            return result;
        }
    }
    public class OperationAdd:Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }
    public class OperationFactory
    {
        public static Operation createOperate(string operate)
        {
            Operation oper = null;
            switch (operate)
            {
                case "+":oper = new OperationAdd(); break;
                default:
                    break;
            }
            return oper;
        }
    }

            Operation oper;
            oper = OperationFactory.createOperate("+");
            oper.NumberA = 3;
            oper.NumberB = 5;
            double result = oper.GetResult();
Policy mode - basic code
  • Policy pattern is a method that defines a series of algorithms, calls all methods in the same way, and reduces the coupling between various algorithm classes and using algorithms.
  class Program
    {
        static void Main(string[] args)
        {
            Context context;

            context = new Context(new ConcreteStrategyA());
            context.ContextInterface();

            context = new Context(new ConcreteStrategyB());
            context.ContextInterface();

            context = new Context(new ConcreteStrategyC());
            context.ContextInterface();

            Console.Read();
        }
    }

    //Abstract algorithm class
    abstract class Strategy
    {
        //Algorithm method
        public abstract void AlgorithmInterface();
    }
    //Specific algorithm A
    class ConcreteStrategyA : Strategy
    {
        //Implementation method of algorithm A
        public override void AlgorithmInterface()
        {
            Console.WriteLine("algorithm A realization");
        }
    }
    //Specific algorithm B
    class ConcreteStrategyB : Strategy
    {
        //Implementation method of algorithm B
        public override void AlgorithmInterface()
        {
            Console.WriteLine("algorithm B realization");
        }
    }
    //Specific algorithm C
    class ConcreteStrategyC : Strategy
    {
        //Algorithm C implementation method
        public override void AlgorithmInterface()
        {
            Console.WriteLine("algorithm C realization");
        }
    }
    //context
    class Context
    {
        Strategy strategy;

        public Context(Strategy strategy)
        {
            this.strategy = strategy;
        }
        //Context interface
        public void ContextInterface()
        {
            strategy.AlgorithmInterface();
        }
    }
  1. Principle of single responsibility
  2. Open closed principle
  3. Dependence Inversion Principle

    • High level modules should not rely on low-level modules, both of which rely on abstraction
    • Abstraction should not depend on details. Details should depend on abstraction
  • The principle of Riemannian substitution: subclasses must be able to replace their parents
    *The parent class can be reused, and the child class can add new behaviors based on the parent class.
  • In fact, dependency inversion is an object-oriented sign. For abstract programming, not for detailed programming, all dependencies end in abstract classes or interfaces, and vice versa, procedural design.
Decoration mode
class Program
    {
        static void Main(string[] args)
        {
            Person xc = new Person("side dish");

            Console.WriteLine("\n First look:");

            Sneakers pqx = new Sneakers();
            BigTrouser kk = new BigTrouser();
            TShirts dtx = new TShirts();

            pqx.Decorate(xc);
            kk.Decorate(pqx);
            dtx.Decorate(kk);
            dtx.Show();

            Console.WriteLine("\n Second look:");

            LeatherShoes px = new LeatherShoes();
            Tie ld = new Tie();
            Suit xz = new Suit();

            px.Decorate(xc);
            ld.Decorate(px);
            xz.Decorate(ld);
            xz.Show();

            Console.WriteLine("\n Third look:");
            Sneakers pqx2 = new Sneakers();
            LeatherShoes px2 = new LeatherShoes();
            BigTrouser kk2 = new BigTrouser();
            Tie ld2 = new Tie();

            pqx2.Decorate(xc);
            px2.Decorate(pqx);
            kk2.Decorate(px2);
            ld2.Decorate(kk2);

            ld2.Show();

            Console.Read();
        }
    }

    class Person
    {
        public Person()
        { }

        private string name;
        public Person(string name)
        {
            this.name = name;
        }

        public virtual void Show()
        {
            Console.WriteLine("Dressed up{0}", name);
        }
    }

    class Finery : Person
    {
        protected Person component;

        //dress up
        public void Decorate(Person component)
        {
            this.component = component;
        }

        public override void Show()
        {
            if (component != null)
            {
                component.Show();
            }
        }
    }


    class TShirts : Finery
    {
        public override void Show()
        {
            Console.Write("large T Shirt ");
            base.Show();
        }
    }

    class BigTrouser : Finery
    {
        public override void Show()
        {
            Console.Write("loose  ");
            base.Show();
        }
    }

    class Sneakers : Finery
    {
        public override void Show()
        {
            Console.Write("Broken shoes ");
            base.Show();
        }
    }

    class Suit : Finery
    {
        public override void Show()
        {
            Console.Write("suit ");
            base.Show();
        }
    }

    class Tie : Finery
    {
        public override void Show()
        {
            Console.Write("necktie ");
            base.Show();
        }
    }

    class LeatherShoes : Finery
    {
        public override void Show()
        {
            Console.Write("leather shoes ");
            base.Show();
        }
    }
  • Decoration mode is a way to dynamically add more functions to existing functions.
  • When the system needs new functions, it is to add new codes to the old classes. These new codes usually decorate the core responsibilities or key behaviors of the original classes, and add new fields, new methods and new logic to the main classes, so as to increase the complexity of the main classes. These newly added things are only to meet some special conditions that can only be executed in a certain situation The need for behavior. The decoration mode puts the decoration function into a separate class, and lets this class wrap the objects it needs to decorate. Remove the decoration function of the class from the class, so as to simplify the original class, effectively distinguish the core responsibility and decoration function of the class, and remove the repeated decoration logic of the related classes.
proxy pattern
    class Program
    {
        static void Main(string[] args)
        {
            SchoolGirl jiaojiao = new SchoolGirl();
            jiaojiao.Name = "Li Jiaojiao";

            Proxy daili = new Proxy(jiaojiao);

            daili.GiveDolls();
            daili.GiveFlowers();
            daili.GiveChocolate();


            Console.Read();
        }
    }

    //giving gifts.
    interface GiveGift
    {
        void GiveDolls();
        void GiveFlowers();
        void GiveChocolate();
    }

    class Proxy : GiveGift
    {
        Pursuit gg;
        public Proxy(SchoolGirl mm)
        {
            gg = new Pursuit(mm);
        }


        public void GiveDolls()
        {
            gg.GiveDolls();
        }

        public void GiveFlowers()
        {
            gg.GiveFlowers();
        }

        public void GiveChocolate()
        {
            gg.GiveChocolate();
        }
    }

    class Pursuit : GiveGift
    {
        SchoolGirl mm;
        public Pursuit(SchoolGirl mm)
        {
            this.mm = mm;
        }
        public void GiveDolls()
        {
            Console.WriteLine(mm.Name + " A doll for you");
        }

        public void GiveFlowers()
        {
            Console.WriteLine(mm.Name + " Send you flowers");
        }

        public void GiveChocolate()
        {
            Console.WriteLine(mm.Name + " Chocolate for you");
        }
    }

    class SchoolGirl
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
  • Remote agent
  • Virtual agent
  • Security agent
  • Intelligent guidance
Factory method mode
 /// <summary>
    ///Operation class
    /// </summary>
    class Operation
    {
        private double _numberA = 0;
        private double _numberB = 0;

        public double NumberA
        {
            get { return _numberA; }
            set { _numberA = value; }
        }

        public double NumberB
        {
            get { return _numberB; }
            set { _numberB = value; }
        }

        /// <summary>
        ///Get the operation result
        /// </summary>
        /// <returns></returns>
        public virtual double GetResult()
        {
            double result = 0;
            return result;
        }
    }

    /// <summary>
    ///Addition class
    /// </summary>
    class OperationAdd : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }

    /// <summary>
    ///Subtraction class
    /// </summary>
    class OperationSub : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA - NumberB;
            return result;
        }
    }
    /// <summary>
    ///Multiplicative class
    /// </summary>
    class OperationMul : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA * NumberB;
            return result;
        }
    }
    /// <summary>
    ///Division class
    /// </summary>
    class OperationDiv : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            if (NumberB == 0)
                throw new Exception("Divisor cannot be 0.");
            result = NumberA / NumberB;
            return result;
        }
    }

    /// <summary>
    ///Factory method
    /// </summary>
    interface IFactory
    {
        Operation CreateOperation();
    }

    /// <summary>
    ///Factory specializing in production of "+"
    /// </summary>
    class AddFactory : IFactory
    {
        public Operation CreateOperation()
        {
            return new OperationAdd();
        }
    }

    /// <summary>
    ///Factory specially responsible for producing "-"
    /// </summary>
    class SubFactory : IFactory
    {
        public Operation CreateOperation()
        {
            return new OperationSub();
        }
    }

    /// <summary>
    ///Factory specializing in production of "*"
    /// </summary>
    class MulFactory : IFactory
    {
        public Operation CreateOperation()
        {
            return new OperationMul();
        }
    }

    /// <summary>
    ///Factory specially responsible for producing "/"
    /// </summary>
    class DivFactory : IFactory
    {
        public Operation CreateOperation()
        {
            return new OperationDiv();
        }
    }
  • When implementing the factory method mode, the client needs to decide which factory to instantiate to implement the operation class. The problem of choosing the judgment still exists. The factory method moves the internal logic judgment of the simple factory to the client code. The function you want to add is to change the factory class, but now it is to modify the client.
Prototype mode
 class Program
    {
        static void Main(string[] args)
        {
            Resume a = new Resume("Big bird");
            a.SetPersonalInfo("male", "29");
            a.SetWorkExperience("1998-2000", "XX company");

            Resume b = (Resume)a.Clone();
            b.SetWorkExperience("1998-2006", "YY enterprise");

            Resume c = (Resume)a.Clone();
            c.SetWorkExperience("1998-2003", "ZZ enterprise");

            a.Display();
            b.Display();
            c.Display();

            Console.Read();

        }
    }

    //resume
    class Resume : ICloneable
    {
        private string name;
        private string sex;
        private string age;

        private WorkExperience work;

        public Resume(string name)
        {
            this.name = name;
            work = new WorkExperience();
        }

        private Resume(WorkExperience work)
        {
            this.work = (WorkExperience)work.Clone();
        }

        //Set up personal information
        public void SetPersonalInfo(string sex, string age)
        {
            this.sex = sex;
            this.age = age;
        }
        //Set up work experience
        public void SetWorkExperience(string workDate, string company)
        {
            work.WorkDate = workDate;
            work.Company = company;
        }

        //display
        public void Display()
        {
            Console.WriteLine("{0} {1} {2}", name, sex, age);
            Console.WriteLine("Work experience:{0} {1}", work.WorkDate, work.Company);
        }

        public Object Clone()
        {
            Resume obj = new Resume(this.work);

            obj.name = this.name;
            obj.sex = this.sex;
            obj.age = this.age;


            return obj;
        }

    }

    //work experience
    class WorkExperience : ICloneable
    {
        private string workDate;
        public string WorkDate
        {
            get { return workDate; }
            set { workDate = value; }
        }
        private string company;
        public string Company
        {
            get { return company; }
            set { company = value; }
        }

        public Object Clone()
        {
            return (Object)this.MemberwiseClone();
        }
    }
  • Shallow copy
Template mode
class Program
    {
        static void Main(string[] args)
        {
            AbstractClass c;

            c = new ConcreteClassA();
            c.TemplateMethod();

            c = new ConcreteClassB();
            c.TemplateMethod();

            Console.Read();

        }
    }

    abstract class AbstractClass
    {
        public abstract void PrimitiveOperation1();
        public abstract void PrimitiveOperation2();

        public void TemplateMethod()
        {
            PrimitiveOperation1();
            PrimitiveOperation2();
            Console.WriteLine("");
        }
    }

    class ConcreteClassA : AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("concrete class A Method 1 implementation");
        }
        public override void PrimitiveOperation2()
        {
            Console.WriteLine("concrete class A Method 2 implementation");
        }
    }

    class ConcreteClassB : AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("concrete class B Method 1 implementation");
        }
        public override void PrimitiveOperation2()
        {
            Console.WriteLine("concrete class B Method 2 implementation");
        }
    }
Appearance mode
class Program
    {
        static void Main(string[] args)
        {
            Facade facade = new Facade();

            facade.MethodA();
            facade.MethodB();

            Console.Read();

        }
    }

    class SubSystemOne
    {
        public void MethodOne()
        {
            Console.WriteLine(" Subsystem method 1");
        }
    }

    class SubSystemTwo
    {
        public void MethodTwo()
        {
            Console.WriteLine(" Subsystem method 2");
        }
    }

    class SubSystemThree
    {
        public void MethodThree()
        {
            Console.WriteLine(" Subsystem method 3");
        }
    }

    class SubSystemFour
    {
        public void MethodFour()
        {
            Console.WriteLine(" Subsystem method 4");
        }
    }

    class Facade
    {
        SubSystemOne one;
        SubSystemTwo two;
        SubSystemThree three;
        SubSystemFour four;

        public Facade()
        {
            one = new SubSystemOne();
            two = new SubSystemTwo();
            three = new SubSystemThree();
            four = new SubSystemFour();
        }

        public void MethodA()
        {
            Console.WriteLine("\n Method group A() ---- ");
            one.MethodOne();
            two.MethodTwo();
            four.MethodFour();
        }

        public void MethodB()
        {
            Console.WriteLine("\n Method group B() ---- ");
            two.MethodTwo();
            three.MethodThree();
        }
    }
Builder pattern
 class Program
    {
        static void Main(string[] args)
        {
            Director director = new Director();
            Builder b1 = new ConcreteBuilder1();
            Builder b2 = new ConcreteBuilder2();

            director.Construct(b1);
            Product p1 = b1.GetResult();
            p1.Show();

            director.Construct(b2);
            Product p2 = b2.GetResult();
            p2.Show();

            Console.Read();
        }
    }

    class Director
    {
        public void Construct(Builder builder)
        {
            builder.BuildPartA();
            builder.BuildPartB();
        }
    }

    abstract class Builder
    {
        public abstract void BuildPartA();
        public abstract void BuildPartB();
        public abstract Product GetResult();
    }

    class ConcreteBuilder1 : Builder
    {
        private Product product = new Product();

        public override void BuildPartA()
        {
            product.Add("parts A");
        }

        public override void BuildPartB()
        {
            product.Add("parts B");
        }

        public override Product GetResult()
        {
            return product;
        }
    }

    class ConcreteBuilder2 : Builder
    {
        private Product product = new Product();
        public override void BuildPartA()
        {
            product.Add("parts X");
        }

        public override void BuildPartB()
        {
            product.Add("parts Y");
        }

        public override Product GetResult()
        {
            return product;
        }
    }

    class Product
    {
        IList<string> parts = new List<string>();

        public void Add(string part)
        {
            parts.Add(part);
        }

        public void Show()
        {
            Console.WriteLine("\n Product creation ----");
            foreach (string part in parts)
            {
                Console.WriteLine(part);
            }
        }
    }

This paper is a platform of operation tools such as blog group sending one article and multiple sending OpenWrite release

Posted by vanzkee on Tue, 16 Jun 2020 20:45:41 -0700