Define an interface for creating an
object, but let sub classes decide which class to instantiate. Factory Method
lets a class defer instantiate to sub classes.
Participants
The classes and/or objects
participating in this pattern are:
- Product (Page)
- Concrete Product (SkillsPage, EducationPage, ExperiencePage)
Implements the Product interface
- Creator (Document)
Declares the factory method, which returns an object of
type Product. Creator may also define a default implementation of the factory
method that returns a default Concrete Product object. May call the factory method to create a Product object.
- Concrete Creator (Report, Resume)
Overrides the factory method to return an instance of a
Concrete Product.
Code Sample:
using System;
namespace Factory.Structural
{
/// <summary>
/// MainApp
startup class for Structural
/// Factory
Method Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry
point into console application.
/// </summary>
static void Main()
{
//
An array of creators
Creator[]
creators = new Creator[2];
creators[0]
= new ConcreteCreatorA();
creators[1]
= new ConcreteCreatorB();
//
Iterate over creators and create products
foreach (Creator creator in creators)
{
Product product
= creator.FactoryMethod();
Console.WriteLine("Created
{0}",
product.GetType().Name);
}
//
Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The 'Product' abstract class
/// </summary>
abstract class Product
{
}
/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ConcreteProductA : Product
{
}
/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ConcreteProductB : Product
{
}
/// <summary>
/// The 'Creator' abstract class
/// </summary>
abstract class Creator
{
public abstract Product FactoryMethod();
}
/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class ConcreteCreatorA : Creator
{
public override Product FactoryMethod()
{
return new ConcreteProductA();
}
}
/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class ConcreteCreatorB : Creator
{
public override Product FactoryMethod()
{
return new ConcreteProductB();
}
}
}
|
Output
Created ConcreteProductA
Created ConcreteProductB |
No comments:
Post a Comment