Programming - Factory Method Design Pattern
Define an interface for creating an object, but let
subclasses decide which class to instantiate. Factory Method
lets a class defer instantiation to subclasses.
The classes and/or objects participating in this example are:
-
Productand
- defines the interface of objects the factory method
creates
-
ConcreteProduct
- implements the Product interface
-
Creatorand
- 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 ConcreteProduct object.
- may call the factory method to create a Product
object.
-
ConcreteCreator
- overrides the factory method to return an instance of
a ConcreteProduct.
|
// Factory Method pattern -- Structural example
|
|
using
System;
using System.Collections;
namespace
DoFactory.GangOfFour.Factory.Structural
{
// MainApp test application
class MainApp
{
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.Read();
}
}
// "Product"
abstract class Product
{
}
// "ConcreteProductA"
class ConcreteProductA : Product
{
}
// "ConcreteProductB"
class ConcreteProductB : Product
{
}
// "Creator"
abstract class Creator
{
public abstract Product
FactoryMethod();
}
// "ConcreteCreator"
class ConcreteCreatorA : Creator
{
public override Product
FactoryMethod()
{
return new
ConcreteProductA();
}
}
// "ConcreteCreator"
class ConcreteCreatorB : Creator
{
public override Product
FactoryMethod()
{
return new
ConcreteProductB();
}
}
}
Output expected:
Created ConcreteProductA
Created ConcreteProductB
and
|