net Design Patterns (Factory Method) Learning Notes

Keywords: Mobile

Use design patterns only to solve one kind of problem. When solving the current one, it usually brings other problems when solving this problem.

net Design Patterns (Factory Method) Learning Notes

  • Summary: Add new creation objects or delete old ones for simple factories. It involves modifying the code in a simple factory. This will bring a lot of uncertain hazards in the actual production environment. According to the principle of "closed to modification and open to expansion". We split simple factories into individual object factories. In this way, we only need to build the corresponding factory room for the newly created objects, and we will not modify the old factory code.

 

Interface:

    public interface IPerson
    {
         string GetColor();
    }


//Three types

    public class Black :IPerson
    {
        public string GetColor()
        {
            return "Black";
        }

    }


    public  class White : IPerson
    {
        public string GetColor()
        {
            return "White";
        }
    }


    public class Yellow : IPerson
    {
        public string GetColor()
        {
            return "Black";
        }
    }


//Separate Realization of Three Factories

    public class BlackFactory
    {
        public static  IPerson CreateInstance()
        {
            IPerson person = new Black();
            return person;
        }
    }


    public class WhiteFactory
    {
        public static IPerson CreateInstance()
        {
            IPerson person = new White();
            return person;
        }
    }

    public class YellowFactory
    {
        public static IPerson CreateInstance()
        {
            IPerson person = new Yellow();
            return person;
        }
    }


//This is what it is now.

    public class Main
    {
        public Main()
        {
            /// Simple Factory
            IPerson yellow = Factory.CreatePerson(Factory.PersonType.Yellow);
            string color = yellow.GetColor();


            ///Factory Method
            IPerson yellow1 = YellowFactory.CreateInstance();
            string color1 = yellow1.GetColor();


        }
  
    }

From the point of view of the current code, in fact, it feels redundant. The direct object new() is just fine. That's true from the current code!

But as the project gets bigger and bigger, the code gets more and more complex. Only in this way can we embody the practicability of the factory method! uuuuuuuuuu It's something you've learned from the actual project.

 

Posted by kireol on Mon, 28 Jan 2019 19:27:14 -0800