设计模式之工厂模式(大话设计模式C++实现)
类图如下:代码实现如下:最近时间比较忙,后期考虑上传到github上。#include<iostream>#include<string>using namespace std;class Operation{public:virtual double getResult()=0;void SetNumberA(double value){NumberA = value;}
·
类图如下:
代码实现如下:最近时间比较忙,后期考虑上传到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;
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献3条内容
所有评论(0)