The following two types of problems can often be encountered in object-oriented system design:
- To improve cohesion and loose coupling, we often abstract some classes of public interfaces to form a base class or interface. This allows us to point to the actual subclass implementation through a pointer to the base class, which achieves the polymorphic purpose. One of the problems here is that too many subclasses inherit from the base class, and we have to write code like newxxx every time we want to use subclasses. Here are two questions: A. The client programmer must know the name of the actual subclass; B. The extensibility and maintenance of the program becomes more and more difficult
- There is also a case where the parent class does not know exactly which specific subclass to instantiate. The meaning of this is that if Class A is to be used to class b,b is an abstract parent class, it is not known in a that the subclass of which B is to be instantiated, but it is known in subclass D of Class A. In a We have no way to directly use similar to NEWXXX, because there is no knowing what XXX is.
The above two questions also lead to the two most important features of the factory model:
- Defines an interface that creates objects, encapsulates the creation of objects
- Yes, the work of the materialized class is deferred to the subclass
1#include <memory>2#include <string>3#include <iostream>4 5 using namespacestd;6 7 classOperation8 {9 Public:TenOperation (DoubleNumbera =0,DoubleNumberb =0): Numbera_ (Numbera), Numberb_ (Numberb) One {} A voidSetnumbera (DoubleNumbera) - { -Numbera_ =Numbera; the } - DoubleGetnumbera (void) - { - returnNumbera_; + } - voidSetnumberb (DoubleNumberb) + { ANumberb_ =Numberb; at } - DoubleGetnumberb (void) - { - returnnumberb_; - } - Virtual DoubleGetResult (void) =0; in protected: - DoubleNumbera_; to Doublenumberb_; + }; - the classOperationadd: PublicOperation * { $ Public:Panax Notoginseng DoubleGetResult (void) - { the returnNumbera_ +numberb_; + } A }; the + classOperationsub: PublicOperation - { $ Public: $ DoubleGetResult (void) - { - returnNumbera_-numberb_; the } - };Wuyi theShared_ptr<operation> Createoperationfactory (Charoperate) - { Wu Switch(operate) - { About Case '+': $ returnMake_shared<operationadd>(); - Case '-': - returnMake_shared<operationsub>(); - default: Acout <<"can not distinguish the operate:"<< operate <<Endl; + returnnullptr; the } - } $ the intMain () the { theshared_ptr<operation> Operateadd = Createoperationfactory ('+'); the if(nullptr = =Operateadd) - { in return-1; the } theOperateadd->setnumbera (20.00); AboutOperateadd->setnumberb (30.00); the thecout << Operateadd->getnumbera () <<" + "<< Operateadd->getnumberb () <<" = "<< Operateadd->getresult () <<Endl; the return 0; + } -
design mode (1)---simple Factory mode