Simple Factory mode in C + + design mode

Source: Internet
Author: User
Tags mul
Simple Factory Definition: Implement a factory function to the other operation class selective invocation, realize the actual needs of the user.

Dividing the required functionality into multiple components can reduce the coupling of the Code and improve code reuse. In the future for a function to change demand, only local modification, not reaching, greatly improve efficiency.

The object-oriented design idea is to reduce the coupling degree of the program through encapsulation, inheritance and polymorphism, while the design pattern is the efficiency bonus of OOP, and the rational use of design pattern can make the program more flexible and easy to modify and reuse.

However, while differentiating functional components is not as good as the more classes, the class is partitioned for encapsulation, but the basis of classification is abstract, and the abstract collection of objects with the same properties and functions is the class.

Here, to implement a calculator with subtraction function to illustrate the implementation and application of the simple factory model.

Test Cases

[Code]int Main () {    //two operands entered by the user and an operator    double number1, number2;    Char Oper;    Std::cout << "Please enter a binary operation expressions (+-*/): \ n";    Std::cin >> number1 >> oper >> number2;    Declaring an Action object    operation<double> *operation = new operation<double>;    Declare the Factory object    factory<double> Factory;    Use the factory class selection operator and return the operand (add minus or multiply or divide)    operation = Factory.createoperate (oper);    Set two operands. (note here that operation is already a specific derived class operation, calling the SetValue method is inherited from the base class)    Operation->setvalue (Number1, number2);    if (Operation! = NULL) {        //evaluates the result, which is actually called the GetResult () method of the derived class that performs the operation. That is, the base class pointer points to the derived class        double result = Operation->getresult ();        Std::cout << "result is:" << result << Std::endl;    } else        std::cout << "input is invalid!\n";//input expression is not valid    return 0;}

Declaration of the class (. h)

[code]//Simple Factory mode---implement a calculator #ifndef _01simplefactory_h_#define _01simplefactory_h_//base class, Op class template templates <typename T    >class operation{protected://inherited by derived class and using T Number1, number2;public://Calculated result virtual T getresult ();  Set two operation values of void SetValue (T, T); };//derived class, addition class template <typename T>class add:public operation<t>{public://specific operation, overriding method of base class T GetResult () o  Verride; };//derived class, subtraction class template <typename t>class sub:public operation<t>{public://specific operation, overriding method of base class T GetResult () o  Verride; };//derived class, multiplication class template <typename t>class mul:public operation<t>{public://specific operation, overriding method of base class T GetResult () o  Verride; };//derived classes, Division class template <typename t>class div:public operation<t>{public://specific operation, overriding method of base class T GetResult () o  Verride; };//simple Factory class template <typename T>class factory{private:operation<t> *operate;public://Create a specific operation class based on the incoming operator. Returns the Operation class object operation<t>* createoperate (const char &op);}; #endif

Implementation of the Class (. cpp)

[Code] #include "01SimpleFactory.h" #include <iostream>//class method implementation template <typename T>void operation<t    >::setvalue (t v1, t v2) {//Set two operation values number1 = v1; Number2 = v2;} Template <typename t>t Operation<t>::getresult () {return 0;}    Template <typename t>t Add<t>::getresult () {T res = number1 + number2; return res;}    Template <typename t>t Sub<t>::getresult () {T res = Number1-number2; return res;}    Template <typename t>t Mul<t>::getresult () {T res = number1 * NUMBER2; return res;}    Template <typename t>t Div<t>::getresult () {Double res = 0;        0 cannot be divisor, can make dividend if (number2! = 0) {res = Number1/number2;    return res;    } std::cout << "0 cannot be used as a divisor\n"; return 0;} The factory method, which is called by the factory function to other operations classes, is based on the function selectivity of the template <typename t>operation<t>* factory<t>::createoperate (const        Char &op) {switch (OP) {case ' + ': operate = new add<t>;Break        Case '-': operate = new sub<t>;        Break        Case ' * ': operate = new mul<t>;        Break        Case '/': operate = new div<t>;    Break        Default:operate = NULL;      Break } return operate;}

The above is the implementation of the simple factory model.

Summarize:

The Create pattern abstracts the instantiation of a class, allowing the creation of objects to be separated from the use of objects.

The simple Factory mode, also known as the static factory method pattern, belongs to the class-creation pattern. In the simple Factory mode, you can return instances of different classes depending on the parameters. The simple factory model specifically defines a class to be responsible for creating instances of other classes, and the instances that are created typically have a common parent class.

The Simple factory model contains three roles: the factory role is responsible for implementing the internal logic of creating all instances; The abstract product role is the parent of all objects created, and is responsible for describing the common interfaces common to all instances; The product role is to create the target, and all created objects act as instances of a specific class of this role.

The point of the simple factory model is that when you need something, just pass in the correct parameter, and you get the object you want without having to know its creation details.

The biggest advantage of the simple factory model is that the object creation and the use of the object separation, the creation of the object to the specialized factory class responsible, but its biggest disadvantage is that the factory class is not flexible enough to add new concrete products need to modify the factory class Judgment logic code, and when the product is more, the factory method code will be very complex.

The simple factory model is suitable for cases where the factory class is responsible for creating fewer objects, and the client only knows the parameters of the incoming factory class and does not care about how to create the object.

The above is the C + + design mode shallow knowledge of simple Factory mode content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.