Simple Factory mode (Simple Factory Pattern):
Defines a factory class that can return instances of different classes depending on the parameters, and the instances that are created usually have a common parent class.
The method used to create an instance in the simple Factory mode is usually static, which is also known as the Static Factory method (Factory) mode
Important: If you need anything, just pass in the correct parameter, and you can get the object you want without having to know its creation details.
This is achieved by code:
The Simple factory model consists of the following 3 roles :
Factory (Factory role)
Product (abstract products role)
Concreteproduct (Specific product role)
// typical abstract Product class code:
Abstract class product{ // Common business method for all product classes public void methodsame () { // implementation of public methods }// Declare abstract business method publicabstractvoid Methoddiff ();}
// typical specific Product class code: class concreteproducta:product{ // Implement business method public override void Methoddiff () { // Implementation of business method }}
//Typical factory-class code:classfactory{//Static Factory Method Public StaticProduct GetProduct (stringArg) {Product Product=NULL; if(Arg. Equals ("A") ) {Product=Newconcreteproducta (); //Initialize the set of product } Else if(Arg. Equals ("B") ) {Product=NewCONCRETEPRODUCTB (); //Initialize the set of product } returnproduct; }}
// Client code: class program{ staticvoid Main (string[] args) { product product; = Factory.getproduct ("A"/// Create product objects from factory class Product. Methodsame (); Product. Methoddiff (); }}
the relationship between two classes A and B should be just a to create B or a to use B, not two relationships. The separation of object creation and use makes the system more consistent with the principle of single responsibility, which facilitates the reuse of functions and the maintenance of the system.
Singleton mode (singleton pattern):
That is, a class has only one instantiation object and provides a global access point to access the instance.
1. The class can have only one instance .
2. You must create this instance yourself .
3. this instance must be provided to the entire system on its own .
The structure of the singleton pattern:
the implementation of the Singleton mode is as follows: 1. private Constructors 2. Static Private member variable (self type) 3. Static Public Factory method
//single-instance mode implementation
ClassSingleton {Private StaticSingleton instance=NULL;//static Private member variable//Private Constructors PrivateSingleton () {}//static public factory method, returning a unique instance Public StaticSingleton getinstance () {if(instance==NULL) Instance=NewSingleton (); returninstance; }}
"Simple factory and Singleton" of object-oriented programming mode