Factory Method Design Pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. This pattern lets a class defer instantiation to subclasses
The Factory Method pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. It promotes loose coupling by eliminating the need to bind application-specific classes into the code.
This implementation demonstrates a document creation system where different types of documents create their specific pages:
- Document (Creator): Abstract class that declares the factory method CreatePages()
- Page (Product): Abstract base class for all page types
- Concrete Creators: Resume and Report classes that implement CreatePages()
- Concrete Products: Various page types like SkillsPage, EducationPage, IntroductionPage, etc.
Document- Abstract creator with factory method CreatePages() and Pages collectionPage- Abstract product base classResume- Concrete creator that creates Skills, Education, and Experience pagesReport- Concrete creator that creates Introduction, Results, Conclusion, Summary, and Bibliography pages- Page implementations:
SkillsPage,EducationPage,ExperiencePage,IntroductionPage,ResultsPage,ConclusionPage,SummaryPage,BibliographyPage
Document[] documents = new Document[2];
documents[0] = new Resume(); // Creates Skills, Education, Experience pages
documents[1] = new Report(); // Creates Introduction, Results, Conclusion, Summary, Bibliography pages
foreach (Document document in documents)
{
Console.WriteLine(document.GetType().Name + "--");
foreach (Page page in document.Pages)
{
Console.WriteLine(" " + page.GetType().Name);
}
}- Eliminates tight coupling between creator and concrete products
- Follows Single Responsibility Principle - object creation is separated from business logic
- Follows Open/Closed Principle - easy to add new document types without modifying existing code
- Provides flexibility in object creation through inheritance
- Each subclass can create objects appropriate to its context