Factory method mode
GOOD: fixed the failure to comply with the open-closed principle in the simple factory model.
The factory method mode moves the selection and judgment to the client for implementation. If you want to add new features, you do not need to modify the original class and directly modify the client.
Example:
# Include <string>
# Include <iostream>
Using namespace std;
// Instance base class, equivalent to Product (for convenience, no abstraction is used)
Class LeiFeng
{
Public:
Virtual void Sweep ()
{
Cout <"Lei Feng sweeping thunder" <endl;
}
};
// A college student studying Lei Feng, equivalent to ConcreteProduct
Class Student: public LeiFeng
{
Public:
Virtual void Sweep ()
{
Cout <"college student sweeping" <endl;
}
};
// Volunteers from Lei Feng, equivalent to ConcreteProduct
Class Volenter: public LeiFeng
{
Public:
Virtual void Sweep ()
{
Cout <"Volunteers are abducted" <endl;
}
};
// Workshop-based Creator
Class LeiFengFactory
{
Public:
Virtual LeiFeng * CreateLeiFeng ()
{
Return new LeiFeng ();
}
};
// Workshop type
Class StudentFactory: public LeiFengFactory
{
Public:
Virtual LeiFeng * CreateLeiFeng ()
{
Return new Student ();
}
};
Class VolenterFactory: public LeiFengFactory
{
Public:
Virtual LeiFeng * CreateLeiFeng ()
{
Return new Volenter ();
}
};
// Client
Int main ()
{
LeiFengFactory * sf = new LeiFengFactory ();
LeiFeng * s = sf-> CreateLeiFeng ();
S-> Sweep ();
Delete s;
Delete sf;
Return 0;
}