Recently I learned the design pattern by myself and found that many books are implemented in java. Because I am engaged in C ++ development, I want to use C ++ to implement it myself and deepen my understanding.
Creator Mode
Definition: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.
Applicability:
1. When creating complex objects, algorithms should be independent of the components of the objects and their assembly methods
2. When the constructor must run a different representation of the constructed object
Structure diagram:
Implementation:
Class Product
{
Public:
VoidSetPartA (int val)
{
M_partA = val;
}
VoidSetPartB (int val)
{
M_partB = val;
}
VoidSetPartC (int val)
{
M_partC = val;
}
VoidshowProperty ()
{
Cout <"show product property:" <
Cout <"m_partA:" <
Cout <"m_partB:" <
Cout <"m_partC:" <
}
Protected:
Private:
Intm_partA;
Intm_partB;
Intm_partC;
};
// Builder does not declare the method as a pure virtual function, so that the customer only needs to redefine the operations of interest.
Class Builder
{
Public:
Virtual void CreateProduct (){};
Virtual void SetPartA (intval ){};
Virtual void SetPartB (intval ){};
Virtual void SetPartC (intval ){};
VirtualProduct * GetProduct ()
{
ReturnNULL;
};
};
Class ConcreteBuilder: public Builder
{
Public:
VoidCreateProduct ()
{
M_product = new Product;
}
VoidSetPartA (int val)
{
Cout <"Build PartA" <
M_product-> SetPartA (val );
}
VoidSetPartB (int val)
{
Cout <"Build PartB" <
M_product-> SetPartB (val );
}
VoidSetPartC (int val)
{
Cout <"Build PartC" <
M_product-> SetPartC (val );
}
Product * GetProduct ()
{
Returnm_product;
}
Protected:
Private:
Product * m_product;
};
Class Director
{
Public:
Director (Builder * buider)
{
M_pBuilder = buider;
}
VoidConstruct ()
{
If (! M_pBuilder)
{
Return;
}
M_pBuilder-> CreateProduct ();
M_pBuilder-> SetPartA (1 );
M_pBuilder-> SetPartB (2 );
M_pBuilder-> SetPartC (3 );
}
Protected:
Private:
Builder * m_pBuilder;
};
Builder * pBuilder = new ConcreteBuilder;
Director * pDirector = new Director (pBuilder );
PDirector-> Construct ();
Product * product = pBuilder-> GetProduct ();
Product-> showProperty ();