标签:
大话设计模式这本书使用 C# 语言写的,我用的是 C++ 语言,最近在看这本书,所以用 C++ 语言走了一遍。
以下是部分笔记,包括代码
若不涉及面向对象这个概念,我们写的简易计算器可能是下面这个样子
//User.cpp --- 客户端 #include "iostream" int main() { using namespace std; cout<<"Input First Number : "; int number_a; cin>>number_a; cout<<"Input your operation : "; char opera; cin>>opera; cout<<"Input Second Number : "; int number_b; cin>>number_b; int avaliable = 1; float result = 0; switch(opera) { case '+': result = number_a + number_b; break; case '-': result = number_a - number_b; break; case '*': result = number_a * number_b; break; case '/': { if(number_b) { result = number_a / number_b; break; } else avaliable = 0; } default: result = 0; } if(avaliable) cout<<"The result is : "<<result<<endl; else cout<<"The Second Number connot be 0 !"<<endl; return 0; }可以看出,很呆板,很麻烦,自能实现特定计算,不可调用,没有移植的可能。
而 C++ 是一种面向对象的语言,下面我们用 OOP 思想来重写这段代码。
下面是一个简单的例子,不是很合题,循序渐进。可配合《大话设计模式》这本书来看。
//Factory.h #ifndef FACTORY_H #define FACTORY_H class operate { public: int number_a; int number_b; char sign; float result; public: float calculate(); }; #endif
//Factory.cpp #include "Factory.h" float operate::calculate() { switch(sign) { case '+': result = number_a + number_b; break; case '-': result = number_a - number_b; break; case '*': result = number_a * number_b; break; case '/': { if(number_b) { result = number_a / number_b; break; } } default: result = 0; } return result; }
//User.cpp --- 客户端 #include "Factory.h" #include "iostream" int main() { using namespace std; operate myOpera; cout<<"Input First Number : "; cin>>myOpera.number_a; cout<<"Input Second Number : "; cin>>myOpera.number_b; cout<<"Input Operate sign : "; cin>>myOpera.sign; float my_result = myOpera.calculate(); cout<<"Result is : "<<my_result<<endl; }
明日再写吧。
标签:
原文地址:http://blog.csdn.net/u010477528/article/details/42269299