9. [C + +] Factory mode

Source: Internet
Author: User

Recall that our previous simple factory model, http://www.cnblogs.com/hanxiao-martin/p/4289502.html

The biggest advantage of the simple factory model is that the factory class contains the necessary logical judgments, according to the client's selection criteria to dynamically instantiate the relevant classes, for the client, to remove the dependence on specific products, in our calculator program, only need to "+" and other symbols to the factory can generate corresponding instances, Then the client can do the operation directly.

But the same, he has a disadvantage, is that the factory class itself is not easy to expand and maintain, for example, now to add a radical calculation, first from operation inherit a root class, this step is not a problem, next to the method of computing factory class add ' case ' branch conditions, This modifies the original class, violates our "open-closed principle", so the factory model comes ...

Factory mode: Defines an interface for creating objects, so that subclasses decide which class to instantiate, and the factory method defers the instantiation of a class to its subclasses.

#include <iostream>using namespacestd;classOperation { Public:    Virtual DoubleGetResult () =0; DoubleM_dnum_a =0; DoubleM_dnum_b =0;};classOperationadd: PublicOperation { Public:    Virtual DoubleGetResult () {DoubleDresult = M_dnum_a +M_dnum_b; returnDresult; }};classOperationsub: PublicOperation { Public:    Virtual DoubleGetResult () {DoubleDresult = M_dnum_a-M_dnum_b; returnDresult; }};classOperationmul: PublicOperation { Public:    Virtual DoubleGetResult () {DoubleDresult = M_dnum_a *M_dnum_b; returnDresult; }};classOperationdiv: PublicOperation { Public:    Virtual DoubleGetResult () {DoubleDresult = m_dnum_a/M_dnum_b; returnDresult; }};classIfactory { Public:    Virtualoperation* createoperate () =0;};classaddfactory: PublicIfactory { Public: Operation*createoperate () {return NewOperationadd (); }};classsubfactory: PublicIfactory { Public: Operation*createoperate () {return Newoperationsub (); }};classmulfactory: PublicIfactory { Public: Operation*createoperate () {return NewOperationmul (); }};classdivfactory: PublicIfactory { Public: Operation*createoperate () {return NewOperationdiv (); }};int_tmain (intARGC, _tchar*argv[]) {Ifactory* Operfactory =NULL; CharcOp; cout<<"Please enter the operator (+-*/...):"<<Endl; CIN>>cOp; Switch(cOp) { Case '+': Operfactory=Newaddfactory ();  Break;  Case '-': Operfactory=Newsubfactory ();  Break;  Case '*': Operfactory=Newmulfactory ();  Break;  Case '/': Operfactory=Newdivfactory ();  Break; }        if(Operfactory! =NULL) {Operation* Poper = operfactory->createoperate (); cout<<"Please enter the first number:"<<Endl; CIN>> poper->M_dnum_a; cout<<"Please enter a second number:"<<Endl; CIN>> poper->M_dnum_b; Try {            DoubleDresult = poper->GetResult (); cout<<"The result is:"<< Dresult <<Endl; } Catch (...) {cout<<"Please enter the correct number of actions"<<Endl; }} system ("PAUSE"); return 0;}

This is my C + + simulation out of the factory model, this example, although the implementation of the factory model, it will choose to determine the problem to the client, so that the client maintenance becomes troublesome, if you want to add new operations, it is changed the factory class, and now is to change the client, it seems to become more troublesome, So why use Factory mode?

When should we use the factory model?

Look at < design mode > Lei Feng's example, there is a Lei Feng class, it has sweeping, laundry, buy rice three methods, now there are three fast graduates to learn Lei Feng do good things, so they will inherit Lei Feng that class, here a simple factory model, there is a simple "Lei Feng Factory"- Simplefactory, the object is instantiated by passing in the arguments. Because studying Lei Feng out of students or social volunteers, so this simple factory class may be like the following:

Then look at the client code:

Well, now the need to come, these three students graduated, they program from college students community volunteers, we need to change the original code, three to create "Lei Feng's college students" into "community volunteers", we need to change three places. Then there will be repeated operations, if changed into a Factory mode to achieve:

Then look at the client code:

At this point, if we change to "community volunteers", just modify the first sentence of the code.

Written at the end:

In fact, when to use a simple factory, when to use the factory, I have not fully understood, the following excerpt from the online analysis:

The factory method model is designed to overcome the drawbacks of the Simple factory model (mainly to meet the OCP). However, the factory method model must be better than the simple factory model? The author's answer is not necessarily. The following is a detailed comparison of the two modes.

    1. Structural complexity from this point of view, it is obvious that the simple factory model to dominate. The simple factory model requires only one factory class, and the factory-mode factory class increases as the number of product classes increases, which undoubtedly increases the number of classes, thus increasing the complexity of the structure.

    2. Code complexity Code complexity and complexity of the structure is a pair of contradictions, since the simple factory model is relatively concise in terms of structure, then it is certainly more complex in code than the factory method mode. Factory classes in simple Factory mode as the product class increases, many methods (or code) are added, while the factory method pattern accomplishes only a single task for each specific factory class, and the code is concise.

    3. Client-side Programming difficulty factory method mode Although the interface is introduced in the factory class structure to satisfy the OCP, the factory class needs to be instantiated in the client code. The factory class of the simple factory model is a static class, which is undoubtedly an attractive advantage when the client does not need to instantiate it.

    4. The difficulty of management is a key issue. Let's talk about extensions first. As we all know, the factory method model completely satisfies the OCP, that is, it has very good extensibility. Does that mean that the simple factory model has no extensibility? The answer is in the negative. The simple factory model also has good extensibility--only a small amount of code (modifying the code of the Factory class) can be extended to meet the extensibility requirements. Although this does not fully meet the OCP, but I think there is no need to be too wedded to the design theory, to know that the Sun provides the official Java Toolkit also think of more than the example of the need to meet the OCP AH (Java.util.Calendar this abstract class does not meet the OCP, specific reasons can be analyzed below).

      Then we analyze it from the standpoint of maintainability. The first is the factory model, if a specific product class needs to make certain changes, it is likely to need to modify the corresponding factory class. When you need to modify multiple product classes at the same time, the modification of the factory class becomes quite cumbersome (it is already a problem). Instead of a simple factory without these troubles, when multiple product classes need to be modified, the simple factory model still needs only to modify the unique factory class (can be changed to meet the requirements anyway?). It's a big deal to rewrite this class).

      From the above analysis, I think the simple factory model is better to use more convenient. Of course, this is only the author's personal views, after all, it is generally accepted that the factory method model is more "advanced" than the simple factory model. But sometimes too advanced things may not suit themselves, this is a matter of opinion.

9. [C + +] Factory mode

Related Article

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.