C/C++教程

设计模式之工厂模式(大话设计模式C++实现)

本文主要是介绍设计模式之工厂模式(大话设计模式C++实现),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

类图如下:

代码实现如下:最近时间比较忙,后期考虑上传到github上。


#include<iostream>
#include<string>
using namespace std;


class Operation{
public:
    virtual double getResult()=0;
    void SetNumberA(double value){
        NumberA = value;
    }
    void SetNumberB(double value){
        NumberB = value;
    }
protected:
    double NumberA;
    double NumberB;
};

class abstractFatory{
public:
    virtual Operation* createOperation()=0;
};



class addOperation:public Operation{
public:
    double getResult(){
        return NumberA+NumberB;
    }
};

class addFactory:public abstractFatory{
public:
    Operation* createOperation(){
        return  new addOperation;
    }
};

class subOperation:public Operation{
public:
    double getResult(){
        return NumberA-NumberB;
    }
};

class subFactory:public abstractFatory{
public:
    Operation* createOperation(){
        return  new subOperation;
    }
};

class mulOperation:public Operation{
public:
    double getResult(){
        return NumberA*NumberB;
    }
};

class mulFactory:public abstractFatory{
public:
    Operation* createOperation(){
        return  new mulOperation;
    }
};

class divOperation:public Operation{
public:
    double getResult(){
        return NumberA/NumberB;
    }
};

class divFactory:public abstractFatory{
public:
    Operation* createOperation(){
        return  new divOperation;
    }
};


int main(){

    abstractFatory* factory=new divFactory;
    Operation* operation=factory->createOperation();
    operation->SetNumberA(16);
    operation->SetNumberB(8);
    std::cout<<operation->getResult()<<std::endl;

}

 

这篇关于设计模式之工厂模式(大话设计模式C++实现)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!