1 the factory pattern
1.1 model derivation
How to instantiate the concrete class code from the application, or encapsulated, so that they do not interfere with other parts of the application?
Pizza OrderPizza (string type)
{
//according to the type of pizza, instantiate the correct concrete class, then assigned to pizza instance variable
If (type. The equals (" cheese "))
{
Pizza=new CheesePizza ();
}
Else if (type) equals (" Greek "))
{
Pizza=new GreekPizza ();
}
Else if (type) equals (" pepperoni "))
{
Pizza=new PepperoniPizza ();
}
Pizza. Prepare ();
Pizza. Bake ();
Pizza. The cut ();
Pizza box ();
Return pizza;
}
Now create the object will be moved to the best orderPizza (), to move the code to create a pizza to another object, founded by the new object full-time pizza, the new object is called
"Factory," below for code!
1.2 code
The class SimplePizzaFactory
{
Pizza createpizza (string type)
{
Pizza Pizza=nullptr;
If (type. The equals (" cheese "))
{
Pizza=new CheesePizza ();
}
Else if (type) equals (" Greek "))
{
Pizza=new GreekPizza ();
}
Else if (type) equals (" pepperoni "))
{
Pizza=new PepperoniPizza ();
}
Return pizza;
}
}
This seems to be moved to another object the question, the question remains, SimplePizzaFactory can have many customers, although at present only orderpizza is its guest
, possibly pizzashopmenu homedelivery, so the code to create the pizza after packing into the class, when after implementing change, you just need to modify this class,
1.3 redo PizzaStore class
The class PizzaStore
{
SimplePizzaFactory factory;
Public PizzaStore (SimplePizzaFactory factory)
{
This. The factory=factory;
}
Public Pizza OrderPizza (string type)
{
Pizza Pizza.
Pizza=factory. Createpizza (type);
Pizza. Prepare ();
Pizza. Bake ();
Pizza. The cut ();
Pizza box ();
Return pizza;
}
}