Let's start with a simple factory, for example:
The first is the parent class
Public Abstract class Pizza {public Abstract string Info (); }}
Sub-class
Public class Cheesepizza:pizza { publicoverridestring Info () { return" Hello, cheese pizza successfully ordered "; } }
Next sub-class
Public class pgpizza:pizza{publicoverridestring Info () {return' Hello, bacon pizza order complete! "}}
Factory class
Public classpizzafactory{ Public StaticPizzaGet(stringtype) {Pizza Pizza=NULL;Switch(Tpye) { Case"Cheese Pizza":p Izza=NewCheesepizza (); Break; Case "Bacon Pizza": Pizza=NewPgpizza (); Break;} returnPizza;} }
Let's talk about a single case.
Defined in "Design patterns:elements of resuable object-oriented Software": Ensure a class only have one Instance,and provide a G Lobal point of access to. Its main feature is not to generate a new instance based on the client program call, but to control the number of instances of a type-the only one. (Design mode-engineering implementation and expansion based on C #, Xiang Wang). In other words, the singleton pattern is guaranteed to have only one instance of the specified class at any given time throughout the life of the application, and provides a global access point for the client to get the instance.
Public classsingleton{Private StaticSingleton instance; PrivateSingleton () {} Public StaticSingleton getinstance () {if(instance==NULL) {instance=NewSingleton (); } returninstance; }}
1) First, the Singleton constructor must be private to ensure that the client program does not produce an instance through the new () operation to achieve the purpose of the singleton;
2) because the lifetime of a static variable is the same as the life cycle of the entire application, you can define a private static global variable instance to hold the unique instance of the class;
3) You must provide a global function access to the instance, and in that function provides the ability to control the number of instances, that is, through the IF statement to determine whether the instance has been instantiated, if not, you can create an instance with new (); otherwise, return an instance directly to the customer.
In this classic mode, the thread is not considered for concurrent acquisition of the instance problem, that is, there may be two threads to obtain the instance instance at the same time, and when it is null, there will be two threads created instance, violating the singleton rule. Therefore, you need to modify the above code.
Simple factories and Singleton in C #