The following example shows the factory method in design patterns:
Class creator
{
Pulic:
Virtual Product * Create (productid );
};
Product * Creator: Create (productid ID)
{
If (ID = mine)
Return new myproduct;
If (ID = Yours)
Return new yourproduct;
// Repeat for remaining products...
Return 0;
}
Class mycreator: Public creator
{
Pulic:
Virtual Product * Create (productid );
};
Product * mycreator: creat (productid ID)
{
If (ID = Yours)
Return new myproduct;
If (ID = mine)
Return new yourproduct;
// N. B.: switched yours and mine
If (ID = theirs)
Return new theirproduct;
Return Creator: Create (ID); // called if all others fail
}
These two examples are examples of the method used to create an instance in the factory method. After careful analysis, we will
We can see that there are several if statements, which are very similar to the policy method. Different parameters have different
Work Method (new object), compare the letter in create in Creator and mycreator
In the subclass mycreator, you can call the create method in the Creator.
In this case, the sub-classes are implemented by themselves. Therefore, the two classes have the decorator design mode.
That is to say, although this is a very simple example, three design patterns are involved:
Factory method, strategy, and decorator)
We can also see that various models are interspersed with each other and interact with each other to form a whole.
External oon
Blog: http://ubunoon.cnblogs.com