// Simple factory Mode
Public abstract class pizza
{}
Public class pizzaA: pizza
{}
Public class pizzaB: pizza
{}
// Currently, this pizza can serve many customers who need pizza Information
Public class simplePizzaFactory
{
Public pizza createPizza (string type)
{
Pizza p = null;
If (type = "")
{
P = new pizzaA ();
}
Else if (type = "B ")
{
P = new pizzaB ();
}
Return p;
}
}
Public class pizzaStore
{
SimplePizzaFactory factory;
Public pizzaStore (simplePizzaFactory factory)
{
This. factory = factory;
}
Public pizza OrderPizza (string type)
{
Return factory. createPizza (type );
// Do somethingelse
}
}
Class Program
{
Static void Main (string [] args)
{
SimplePizzaFactory factory = new simplePizzaFactory ();
PizzaStore store = new pizzaStore (factory );
Store. OrderPizza ("");
Console. Read ();
}
}
// Design Pattern principle: dependent on abstraction, not specific classes
// Factory method mode
// Defines an interface for object creation, but the subclass determines which class to instantiate
// The Factory method delays class Instantiation to subclass
Public abstract class pizza
{}
Public class pizzaA: pizza
{}
Public class pizzaB: pizza
{}
// This is the abstract creator class, which defines an abstract factory Method
// Let the subclass implement this method to create a product
Public abstract class pizzaStore
{
Protected abstract pizza CreatePizza (string type );
Public pizza OrderPizza (string type)
{
Pizza p = CreatePizza (type );
// Do somethingelse
Return p;
}
}
Public class StoreA: pizzaStore
{
Protected override pizza CreatePizza (string type)
{
If (type = "")
{
Return new pizzaA ();
}
Else if (type = "B ")
{
Return new pizzaB ();
}
Else return null;
}
}
Class Program
{
Static void Main (string [] args)
{
PizzaStore storeA = new StoreA ();
StoreA. OrderPizza ("");
Console. Read ();
}
}