P2: 디자인 패턴 프로그래밍

생성 - 팩토리 메소드 패턴



팩토리 메서드 패턴은 하위 클래스가 생성할 객체를 결정하도록 하여 객체 생성을 캡슐화합니다. 다음은 이 패턴이 작동하는 방식을 보여주는 클래스 다이어그램입니다.




This self explanatory UML diagram is the example stated in Head First Design Pattern.


문제 설명



안녕 얘들아, 내 Simple Pizza Factory와 함께 내 이야기를 따라와줘서 기쁘다. 나는 큰 성공을 거두었고 New YorkCalifornia에서 내 피자 가게의 프랜차이즈를 시작할 제안을 받았다.

이 프랜차이즈에 대한 내 코드를 수정하기 전에 내 quality control rulescost calculation를 나열하고 싶습니다. 그들이 내 고객에게 제공하는 품질을 유지하지 않음으로써 내 이름을 오용하는 것을 원하지 않기 때문입니다. 자유롭게 주문을 받고 경쟁을 기반으로 피자를 발명하세요.

프랜차이즈 요건


  • 피자가 동일한 방식으로 준비되도록 모든 프랜차이즈 피자 매장에서 내 PizzaStore 코드를 활용하기를 원합니다.
  • NY 스타일 피자는 얇은 크러스트, 맛있는 소스 및 작은 치즈를 사용합니다. (요구 사항에 따라)
  • 시카고 스타일 피자는 두꺼운 크러스트, 풍부한 소스 및 엄청난 양의 치즈를 사용합니다. (요구 사항에 따라)
  • 피자 커팅 및 박싱 실수를 방지하기 위한 품질 관리가 필요합니다.

  • 해결책



    피자 가게에서 모든 피자 만들기 활동을 현지화하는 방법이 있습니다.
    먼저 Pizza Store의 변경 사항을 살펴보겠습니다.

    // Making Pizza Store abstract helped me to move our CreatePizza logic
    // to sub classes (NYStylePizzaStore) (ChicagoStylePizzaStore)
    public abstract class PizzaStore
    {
        public IPizza OrderPizza(string type)
        {
            IPizza pizza;
            pizza = CreatePizza(type);
    
            pizza.prepare();
            pizza.bake();
            pizza.cut();
            pizza.box();
    
            return pizza;
        }
    
        // All the responsibility for instantiating Pizzas has been moved into
        // a method that acts as a factory.
        public abstract IPizza CreatePizza(string type);  // Now this method will create factory.
    
        // Other methods here
    }
    


    One more thing I want to change in my PizzaStore, I have to change my IPizza Interface to Pizza abstract class, with the help of which I can force the steps required in pizza making process. This abstract class will help my franchises to follow the basic steps mention in this abstract class and can override their step if they want to update the process.



    public abstract class Pizza
    {
        public abstract string name { get; set; }
        public abstract string dough { get; set; }
        public abstract string sauce { get; set; }
        public abstract List<string> toppings { get; set; }
        public virtual void prepare()
        {
            Console.WriteLine("Preparing " + name);
            Console.WriteLine("Tossing dough...");
            Console.WriteLine("Adding sauce...");
            Console.WriteLine("Adding toppings: ");
            foreach (string topping in toppings)
            {
                Console.WriteLine(" " + topping);
            }
        }
        public virtual void bake()
        {
            Console.WriteLine("Bake for 25 minute at 350.");
        }
        public virtual void cut()
        {
            Console.WriteLine("Cutting the pizza into diagonal slices.");
        }
        public virtual void box()
        {
            Console.WriteLine("Place pizza in official PizzaStore box.");
        }
        public string getName()
        {
            return name;
        }
    }
    


    You must be wondering how this will help me, wait for a min and look into some of the pizza class.



    // My NY Style Sauce and Cheese Pizza
    public class NYStyleCheesePizza : Pizza
    {
        public override string name { get; set; }
        public override string dough { get; set; }
        public override string sauce { get; set; }
        public override List<string> toppings { get; set; }= new List<string>();
        public NYStyleCheesePizza()
        {
            name = "NY Style Sauce and Cheese Pizza";
            dough = "Thin Crust Dough";
            sauce = "Marinara Sauce";
            toppings.Add("Grated Reggiano Cheese");
        }
    }
    
    // My Chicago Style Sauce and Cheese Pizza
    public class ChicagoStyleCheesePizza : Pizza
    {
        public override string name { get; set; }
        public override string dough { get; set; }
        public override string sauce { get; set; }
        public override List<string> toppings { get; set; } = new List<string>();
        public ChicagoStyleCheesePizza()
        {
            name = "Chicago Style Deep Dish Cheese Pizza";
            dough = "Extra Thick Crust Dough";
            sauce = "Plum Tomato Sauce";
            toppings.Add("Shredded Mozzarella Cheese");
        }
        public override void cut()
        {
            Console.WriteLine("Cutting the pizza into square slices.");
        }
    }
    


    In the above implementation you can see the difference from Simple Factory to Factory Method.



    용법



    당신은 충분히 오래 기다렸습니다. 피자 먹을 시간이야!

    $ cd FactoryMethod
    $ dotnet build
    $ dotnet run
    Welcome to my Pizza Store!
    Please enter your pizza type from
    (Cheese)(Clam)
    
    Cheese
    
    Preparing NY Style Sauce and Cheese Pizza
    Tossing dough...
    Adding sauce...
    Adding toppings:
    Grated Reggiano Cheese
    
    Bake for 25 minute at 350.
    
    Cutting the pizza into diagonal slices.
    
    Place pizza in official PizzaStore box.
    
    Thank for Ordering FactoryMethod.PizzaItems.Types.NYStyleCheesePizza please collect your order from front desk in 15 min
    
    Preparing Chicago Style Deep Dish Cheese Pizza
    
    Tossing dough...
    Adding sauce...
    Adding toppings:
     Shredded Mozzarella Cheese
    
    Bake for 25 minute at 350.
    
    Cutting the pizza into square slices. 
    
    Place pizza in official PizzaStore box.
    Thank for Ordering FactoryMethod.PizzaItems.Types.ChicagoStyleCheesePizza please collect your order from front desk in 15 min
    


    앞으로 나아가 다



    만세! 내 피자 프랜차이즈는 내 상점을 만들기 위해 쏟은 ​​엄청난 노력에 대해 나에게 감사하고 있습니다.

    당신의 견해를 공유하십시오



    디자인 패턴에 대해 더 많은 글을 쓰고 싶다면 자유롭게 의견을 말해주세요. 고맙게 생각합니다.
    또한 배우고 싶은 패턴을 언급하십시오.

    이제 내 상점이 인기를 얻고 있으며 피자 상점과의 호환성을 좀 더 구현하기 위해 Abstract Factory Pattern를 찾을 것입니다.

    좋은 웹페이지 즐겨찾기