디자인 패턴: 공장
개요
정의
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:
- Abstract Factory class.
- Defines an abstract Create method. In some cases, this may include a default implementation.
- Concrete Factory classes.
- Implements the Create method (this will instantiate the Factory's Product objects).
- Abstract Product.
- Defines the Product properties and methods.
- 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
예제 코드 - 장부 생성
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
이제 기본 클래스에 작성된 생성 코드를 수정하지 않고도 다른 책과 페이지를 유연하게 추가할 수 있음을 알 수 있습니다. 다른 책을 추가하려면 Factory 클래스가 다른 책 유형을 처리하도록 하기만 하면 됩니다.
면책 조항: 디자인 패턴을 학습하기 위한 많은 리소스가 있으며 다양한 방식으로 구현할 수 있습니다. 이 게시물을 마치면 더 많은 리소스를 탐색하는 것이 좋습니다.
Reference
이 문제에 관하여(디자인 패턴: 공장), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/ryhenness/design-patterns-factory-3eif
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
To achieve the Factory pattern, there are 4 types of classes we need to implement:
- Abstract Factory class.
- Defines an abstract Create method. In some cases, this may include a default implementation.
- Concrete Factory classes.
- Implements the Create method (this will instantiate the Factory's Product objects).
- Abstract Product.
- Defines the Product properties and methods.
- 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
예제 코드 - 장부 생성
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
이제 기본 클래스에 작성된 생성 코드를 수정하지 않고도 다른 책과 페이지를 유연하게 추가할 수 있음을 알 수 있습니다. 다른 책을 추가하려면 Factory 클래스가 다른 책 유형을 처리하도록 하기만 하면 됩니다.
면책 조항: 디자인 패턴을 학습하기 위한 많은 리소스가 있으며 다양한 방식으로 구현할 수 있습니다. 이 게시물을 마치면 더 많은 리소스를 탐색하는 것이 좋습니다.
Reference
이 문제에 관하여(디자인 패턴: 공장), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/ryhenness/design-patterns-factory-3eif
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
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
Reference
이 문제에 관하여(디자인 패턴: 공장), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ryhenness/design-patterns-factory-3eif텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)