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