Factory method mode
Definition: defines an interface for creating objects, so that the subclass determines which class to instantiate. The factory method delays the instantiation of a class to its subclass.
Applicability:
1. When a class does not know the class of the object it must create
2. When a class wants its subclass to specify the object it creates
3. When the class delegates the responsibility of creating an object to one of multiple help subclasses, and you want to localize the information of which help subclass is the proxy
Advantages:
1. Good Encapsulation
2. excellent scalability
3. Product classes are blocked, so you do not need to know the product class instantiation process.
4. Achieve decoupling and comply with the dimit rule
Structure diagram:
Implementation:
Class Product
{
Public:
Virtual void fun () = 0;
Protected:
Private:
};
Class ConcreteProductA: public Product
{
Public:
Voidfun ()
{
Cout <"ConcreteProductA" <
}
Protected:
Private:
};
Class ConcreteProductB: public Product
{
Public:
Voidfun ()
{
Cout <"ConcreteProductB" <
}
Protected:
Private:
};
Class Creator
{
Public:
VirtualProduct * CreateProductMethod (int type) = 0;
Protected:
Private:
};
Class ConcreteCreator: public Creator
{
Public:
Product * CreateProductMethod (int type );
Protected:
Private:
};
Product * ConcreteCreator: CreateProductMethod (int type)
{
Switch (type)
{
Case 0:
Returnnew ConcreteProductA;
Case 1:
Returnnew ConcreteProductB;
Default:
ReturnNULL;
}
}
If you do not want to create a subclass of the Creator, you can use a template class.
Class Creator
{
Public:
VirtualProduct * CreateProductMethod () = 0;
Protected:
Private:
};
Template
Class TemplateCreator: public Creator
{
Public:
Product * CreateProductMethod ();
};
Template
Product * TemplateCreator : CreateProductMethod ()
{
Return new T;
}
TemplateCreator ACreator;
TemplateCreator BCreator;
Product * pa = ACreator. CreateProductMethod ();
Product * pb = BCreator. CreateProductMethod ();
Pa-> fun ();
Pb-> fun ();
Extension:
1. Simple factory method; sometimes we don't need to instantiate the factory class. You can remove the Creator and do not inherit it. Instead, use the static method directly.
Class ConcreteCreator
{
Public:
StaticProduct * CreateProductMethod (int type );
Protected:
Private:
};
Product * ConcreteCreator: CreateProductMethod (int type)
{
Switch (type)
{
Case 0:
Returnnew ConcreteProductA;
Case 1:
Returnnew ConcreteProductB;
Default:
ReturnNULL;
}
}
Product * pa = ConcreteCreator: CreateProductMethod (0 );
Product * pb = ConcreteCreator: CreateProductMethod (1 );
Pa-> fun ();
Pb-> fun ();