디자인 패턴: 공장

15839 단어 learningbeginners
요요! 디자인 패턴을 배우기 시작하면서 쓰는 두 번째 글입니다. 내 첫 번째 게시물은 싱글톤 패턴을 다루었습니다. 당신은 그것을 찾을 수 있습니다. 이번에는 또 다른 생성 패턴인 Factory 패턴을 살펴보겠습니다. 먼저 정의를 방문한 다음 패턴의 구현을 살펴보고 몇 가지 예제 코드를 살펴보고 마무리하겠습니다.


개요


  • Definition
  • Implementation
  • Example Code - Creating Books



  • 정의

    Factory: a building or group of buildings where goods are manufactured. Like I said earlier, the Factory pattern is a creational pattern and it gives us flexibility in creating different types of objects that inherit from the same class, and then use those objects within the same code.

    We use a Factory and Product relationship to make up this pattern. The Factory takes care of instantiating the Products that it wants to produce, and the Products just need to know what rules they need to follow in order to be a product.


    구현

    To achieve the Factory pattern, there are 4 types of classes we need to implement:

    1. Abstract Factory class.
      • Defines an abstract Create method. In some cases, this may include a default implementation.
    2. Concrete Factory classes.
      • Implements the Create method (this will instantiate the Factory's Product objects).
    3. Abstract Product.
      • Defines the Product properties and methods.
    4. Concrete Product class (this will be instantiated by the Factory objects).
      • Inherits from the Product class, defines the unique Product.

    This pattern allows us to defer the creation of the Product objects to the subclasses of Factory, making it a creational pattern that gives our code flexibility.

    Using C#, the pattern looks like this:

    using System;
    
    public class Program
    {
        public static void Main()
        {
    
        }
    }
    
    abstract class Factory
    {
       public abstract Product Create();
    }
    
    class FactoryA : Factory
    {
        public override Product Create()
        {
            return new ProductA();
        }
    }
    
    class FactoryB : Factory
    {
        public override Product Create()
        {
            return new ProductB();
        }
    }
    
    abstract class Product
    {
        public string Name;
    }
    
    class ProductA : Product
    {
        public ProductA()
        {
            this.Name = "Pepsi";
        }
    }
    
    class ProductB : Product
    {
        public ProductB()
        {
            this.Name = "Coke";
        }
    }
    
    Output:
    FactoryA created Pepsi
    FactoryB created Coke
    

    You can play with this code here on .NET Fiddle




    예제 코드 - 장부 생성

    Now let's take a look at a real world example. Perhaps we want to create a program that helps users create different types of Books. For now, this program will help the user create a Novel, or a History book. Novels will be composed of Pages: Title Page, Event, and About the Author. History books will be composed of Pages: Acknowledgments, Units, and Glossary. The program will then print out the Pages of the book they decided to create (using the same code no matter which book type that the user chose).

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Welcome to Book creator!");
            Console.WriteLine("Would you like to make a Novel or History book?");
            string bookType = Console.ReadLine();
            BookFactory bookFactory = new CoolBookFactory(bookType);
            Book userBook = bookFactory.Create();
            // The magic of the pattern is below:
            Console.WriteLine("PAGES -----");
            foreach (var page in userBook.pages)
            {
                Console.WriteLine(page.GetType().Name);
            }
        }
    }
    
    abstract class BookFactory
    {
        public abstract Book Create();
    }
    
    class CoolBookFactory : BookFactory
    {
        public string BookType { get; private set; }
    
        public CoolBookFactory(string bookType)
        {
            this.BookType = bookType;
        }
    
        public override Book Create()
        {
            if (this.BookType == "Novel")
                return new NovelBook();
            if (this.BookType == "History")
                return new HistoryBook();
    
            return null;
        }
    }
    
    abstract class Book
    {
        public List<Page> pages = new List<Page>();
    }
    
    class NovelBook : Book 
    {
        public NovelBook()
        {
            this.pages.Add(new TitlePage());
            this.pages.Add(new EventPage());
            this.pages.Add(new AboutTheAuthorPage());
        }
    }
    
    class HistoryBook : Book
    {
        public HistoryBook()
        {
            this.pages.Add(new AcknowledgmentsPage());
            this.pages.Add(new UnitsPage());
            this.pages.Add(new GlossaryPage()); 
        }
    }
    
    abstract class Page {}
    class TitlePage : Page {}
    class EventPage : Page {} 
    class AboutTheAuthorPage : Page {}
    class AcknowledgmentsPage: Page {}
    class UnitsPage : Page {} 
    class GlossaryPage : Page {}
    
    Output:
    Welcome to Book creator!
    Would you like to make a Novel or History book?
    Novel
    PAGES -----
    TitlePage
    EventPage
    AboutTheAuthorPage
    

    You can play with this code here on .NET Fiddle



    이제 기본 클래스에 작성된 생성 코드를 수정하지 않고도 다른 책과 페이지를 유연하게 추가할 수 있음을 알 수 있습니다. 다른 책을 추가하려면 Factory 클래스가 다른 책 유형을 처리하도록 하기만 하면 됩니다.




    면책 조항: 디자인 패턴을 학습하기 위한 많은 리소스가 있으며 다양한 방식으로 구현할 수 있습니다. 이 게시물을 마치면 더 많은 리소스를 탐색하는 것이 좋습니다.

    좋은 웹페이지 즐겨찾기