A simple factory model -- Design Model Study Notes

Source: Internet
Author: User

The simple factory mode mainly uses the class polymorphism to create the corresponding subclass in the factory according to different requirements for different results.

A class chart with a simple calculator as an Example

The implementation of the operationfactory class in the figure is roughly as follows:

1 class operationfactory
2 {
3 public:
4 operation * createoperation (STD: String operator)
5 {
6 operation * poper = NULL;
7 switch (operator)
8 {
9 case '+ ':
10 poper = new operationadd;
11 break;
12 case '-':
13 poper = new operationsub;
14 break;
15 case '*':
16 poper = new operationmul;
17 break;
18 case '/':
19 poper = new operationdiv;
20 break;
21}
22 return poper;
23}
24 };

Call the getresult () method based on the returned pointer to obtain the result.

To add other operations, you only need to create a new operation class to implement the operation interface, and then add a case in the factory to instantiate the object.

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.