首页 > 代码库 > 简单工厂模式
简单工厂模式
业务逻辑.h
#pragma once class Operation { protected: double numberA; double numberB; double result; public: void setValue(double numberA, double numberB) { this->numberA = numberA; this->numberB = numberB; } virtual double getValue() = 0; }; class OperationAdd :public Operation { public: double getValue() { result = numberA + numberB; return result; } }; class OperationSub :public Operation { public: double getValue() { result = numberA - numberB; return result; } };
简单工厂.h
#pragma once #include "业务逻辑.h" class OperationFactory { public: static Operation* CreateOperation(char operate) { Operation *oper; switch (operate) { case ‘+‘: oper = new OperationAdd; return oper; break; case ‘-‘: oper = new OperationSub; return oper; break; } } };
界面逻辑.cpp
#include <iostream> using namespace std; #include "工厂.h" int main() { double numberA; double numberB; char operate; cout << "请输入a+b的式子:" << endl; cin >> numberA >> operate >> numberB; Operation *oper; oper = OperationFactory::CreateOperation(operate); oper->setValue(numberA, numberB); cout << "结果为" << oper->getValue() << endl; system("pause"); return 0; }
本文出自 “sophoso的cs学习之路” 博客,请务必保留此出处http://sophoso.blog.51cto.com/9442872/1565682
简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。