static void Main(string[] args) { //BuilderExample(); //FactoryExample(); FactoryMethodExample();
//Console.WriteLine("Hello World!"); Console.ReadKey(); }
static void FactoryMethodExample() { Document[] documents = new Document[2]; documents[0] = new Resume(); documents[1] = new Report();
foreach(Document document in documents) { Console.WriteLine(string.Format("{0}--", document.GetType().Name));
foreach(IPage page in document.Pages) { Console.WriteLine(string.Format("Page : {0}", page.GetType().Name)); } } }
main.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Patterns.FactoryMethod { public interface IPage { } }
IPage.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Patterns.FactoryMethod.Pages { public class BibliographyPage : IPage { } }
BibliographyPage.cs |
BibliographyPage를 포함한 Page들은 구조 동일
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Patterns.FactoryMethod { public abstract class Document { private List<IPage> pages = new List<IPage>(); public abstract void CreatePages();
public List<IPage> Pages => pages;
public Document() { this.CreatePages(); } } }
Document.cs |
using System; using System.Collections.Generic; using System.Text; using DesignPatterns.Patterns.FactoryMethod.Pages;
namespace DesignPatterns.Patterns.FactoryMethod { public class Report : Document { public override void CreatePages() { Pages.Add(new IntroductionPage()); Pages.Add(new ResultsPage()); Pages.Add(new ConclusionPage()); Pages.Add(new SummaryPage()); Pages.Add(new BibliographyPage()); } } }
Report.cs |
using System; using System.Collections.Generic; using System.Text; using DesignPatterns.Patterns.FactoryMethod.Pages;
namespace DesignPatterns.Patterns.FactoryMethod { public class Resume : Document { public override void CreatePages() { Pages.Add(new SkillsPage()); Pages.Add(new EducationPage()); Pages.Add(new ExperiencePage()); } } }
Resume.cs |
참고 사이트
https://www.dofactory.com/net/factory-method-design-pattern
'C# 디자인패턴' 카테고리의 다른 글
06# Prototype 패턴 Creational Patterns (0) | 2019.05.23 |
---|---|
05# Factory Method 패턴2 Creational Patterns (0) | 2019.05.23 |
03# 추상 팩토리(Abstract Factory) 패턴 Creational Patterns (0) | 2019.05.22 |
02# Builder 패턴 Creational Patterns (0) | 2019.05.22 |
01# 싱글턴(Singleton) 패턴 (0) | 2016.04.18 |