Our IT staff have more or less heard of the simple factory model, but how much he knows, we may not know for ourselves, below, let us learn some of the simple factory knowledge.
1. Simple Factory mode
is a creation mode , also known as the Static factory methods (static Factory method) mode, but does not belong to one of the 23 gof design patterns. A simple factory model is a factory object that determines which product class instances are created. Simple Factory mode is the simplest and most practical mode in the factory model family, which can be understood as a special implementation of different factory patterns.
Here's a schematic of a simple factory:
Let's write an example to deepen our understanding:
The following example is the process of ordering pizza using the Simple factory principle:
1. Let's start by creating a form
2. Then create a parent class (pizza) and several pizza subclasses (the parent class is an abstract class, subclass override Overrides)
public class Pgpizza:pizza { public override string info () { return You have successfully ordered Bacon pizza " ; } }
Public class Cheesepizza:pizza { publicoverridestring info () { return" you have successfully ordered Cheese pizza "; } }
3. Then there is a factory class that provides a way to produce pizza (this method has three points to note: Static---Return value type is the parent class type----generally takes one parameter)
Public classPizzafactory {
Public Static PizzaGetInfo (string type) {Pizza Pizza=NULL; Switch(type) { Case "Cheese Pizza": Pizza=NewCheesepizza (); Break; Case "Bacon Pizza": Pizza=NewPgpizza (); Break; } returnPizza; } }
4. Finally call the method through the main form
Private voidBtnok_click (Objectsender, EventArgs e) { //Accept Order Text if(Rbncheese. Checked) {Pizza P=Pizzafactory.getinfo (Rbncheese. Text); stringWord =P.info (); MessageBox.Show (word); } Else if(RBNPG. Checked) {Pizza P=Pizzafactory.getinfo (RBNPG. Text); stringWord =P.info (); MessageBox.Show (word); } }
2. Single-case mode
In some special occasions, we need to only reside in memory of a class of an object,KTV song system, play the form only need to have one.
This will use a singleton pattern.
Come here today, see you next time!!!
Simple factory-------and-----Singleton mode