Home > Backend Development > C#.Net Tutorial > A brief introduction to C++ design patterns and simple factory pattern

A brief introduction to C++ design patterns and simple factory pattern

黄舟
Release: 2017-01-18 15:05:42
Original
1260 people have browsed it

Simple factory definition: Implement a factory function to selectively call other operation classes to meet the actual needs of users.

Dividing required functions into multiple components can reduce code coupling and improve code reuse. When the demand for a certain function changes in the future, only partial modifications are needed, so that the entire system is not affected, which greatly improves efficiency.

The object-oriented design idea is to reduce the coupling of the program through encapsulation, inheritance, and polymorphism, while design patterns increase the efficiency of OOP. Proper use of design patterns can make programs more flexible, easy to modify, and reuse.

However, when distinguishing functional components, it is not that the more classes, the better. Classes are divided for encapsulation, but the basis of classification is abstraction. An abstract collection of objects with the same attributes and functions is a class.

Here, we will implement a calculator with addition, subtraction, multiplication and division functions to illustrate the implementation and application of the simple factory pattern.

Test case

[code]int main(){
    //用户输入的两个操作数和一个操作符
    double number1, number2;
    char oper;
    std::cout << "Please enter a binary operation expressions(+-*/):\n";
    std::cin >> number1 >> oper >> number2;
    //声明操作对象
    Operation<double> *operation = new Operation<double>;
    //声明工厂对象
    Factory<double> factory;
    //利用工厂类选择运算符并返回运算对象(加减还是乘或除?)
    operation = factory.createOperate(oper);
    //设置两个操作数.(此处注意operation已经是具体的派生类运算,调用setValue方法是继承自基类的)
    operation->setValue(number1, number2);
    if(operation != NULL){
        //计算结果,此处实际调用的是执行运算的派生类的getResult()方法。即基类指针指向派生类
        double result = operation->getResult();
        std::cout << "Result is: " << result << std::endl;
    }else
        std::cout << "Input is invalid!\n";//输入表达式不合法

    return 0;
}
Copy after login

Class declaration (.h)

[code]//简单工厂模式---实现一个计算器
#ifndef _01SIMPLEFACTORY_H_
#define _01SIMPLEFACTORY_H_
//基类, 运算类模板
template <typename T>
class Operation{
protected:
    //被派生类继承并使用
    T number1, number2;
public:
    //计算结果
    virtual T getResult();
    //设置两个运算值
    void setValue(T , T );  
};

//派生类, 加法类
template <typename T>
class Add: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//派生类, 减法类
template <typename T>
class Sub: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//派生类, 乘法类
template <typename T>
class Mul: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//派生类, 除法类
template <typename T>
class Div: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//简单工厂类
template <typename T>
class Factory{
private:
    Operation<T> *operate;
public:
    //根据传入的操作符,创建具体的运算类。返回运算类对象
    Operation<T>* createOperate(const char &op);
};
#endif
Copy after login

Class implementation (.cpp)

[code]#include "01SimpleFactory.h"
#include <iostream>
//类方法实现
template <typename T>
void Operation<T>::setValue(T v1, T v2){//设置两个运算值
    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不能作除数,可以作被除数
    if(number2 != 0){
        res = number1 / number2;
        return res;
    }
    std::cout << "0 cannot be used as a divisor\n";
    return 0;
}
//工厂方法,即工厂函数对其他操作类根据功能选择性的调用
template <typename T>
Operation<T>* Factory<T>::createOperate(const char &op){
    switch(op){
    case &#39;+&#39;:
        operate = new Add<T>;
        break;
    case &#39;-&#39;:
        operate = new Sub<T>;
        break;    
    case &#39;*&#39;:
        operate = new Mul<T>;
        break;    
    case &#39;/&#39;:
        operate = new Div<T>;
        break;
    default:
        operate = NULL;
        break;  
    }
    return operate;
}
Copy after login

The above is the implementation of the simple factory pattern.

Summary:

The creational pattern abstracts the instantiation process of a class and can separate the creation of objects from the use of objects.

The simple factory pattern is also called the static factory method pattern, which belongs to the class creation pattern. In the simple factory pattern, instances of different classes can be returned according to different parameters. The simple factory pattern specifically defines a class to be responsible for creating instances of other classes. The created instances usually have a common parent class.

The simple factory pattern contains three roles: the factory role is responsible for implementing the internal logic of creating all instances; the abstract product role is the parent class of all objects created and is responsible for describing the public interface common to all instances; the specific product role is the creation target , all objects created act as instances of a concrete class in this role.

The key point of the simple factory pattern is: when you need something, you only need to pass in a correct parameter to get the object you need without knowing the details of its creation.

The biggest advantage of the simple factory pattern is to separate the creation of objects and the use of objects, and leave the creation of objects to a specialized factory class. However, its biggest disadvantage is that the factory class is not flexible enough. Adding new specific products requires modifying the factory. The judgment logic code of the class, and when there are many products, the factory method code will be very complicated.

The applicable situations of the simple factory pattern include: the factory class is responsible for creating relatively few objects; the client only knows the parameters passed into the factory class and does not care about how to create the objects.

The above is the content of a brief introduction to the simple factory pattern in C++ design patterns. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template