A simple example of Design Pattern Analysis

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.