模板方法 Templete Method 实际的处理交给子类,让别人去干吧。
2014-03-20 11:24
351 查看
// example11.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "string.h" //总而言之,要抽象,初期不要太多的关注细节,否则你就会陷入泥潭, //在做设计的时候,就想着实现不归你来负责,那是别人的事情,能多抽象就多抽象, //俗话说,站得高,看的远。你看那个老板自己做具体工作。这个结论说的有点过了,当然肯定也有。 //在设计过程中,不要沉迷于具体实现,要先考虑要实现什么功能, //看下边这个例子,按照如下格式输出一下两种图案 /* <<HHHHH>> ----------- hello world hello world hello world hello world hello world ----------- */ /*看到这两个图案,你如何实现呢? 我想我们大部分人都上来就干,这很正常,我也这样.但我们确实不应该这样,这个习惯要慢慢改变 先抽象吧,干这件事情要三步,先输出了<<和-------------, 再重复H 5遍, hello world 5遍,最后>> 和 ---------------- 所以抽象完成了,firstoutput, secondoutput, thirdoutput, 再把三个组装在一起,不就ok了吗,先不管咋实现,那是别人的事情 */ class output { private: virtual void firstoutput() = 0; virtual void secondoutput() = 0; virtual void thirdoutput() = 0; public: void printtoscreen() { firstoutput(); secondoutput(); thirdoutput(); }; }; /* 老板说,实现也要我来搞,这下苦逼了,那为了生存,就干吧 */ class outputH : public output { public: outputH(char ch) { m_ch = ch; }; void firstoutput() { printf("<<"); }; void secondoutput() { for(int i=0; i<5; i++) { printf("%c", m_ch); } }; void thirdoutput() { printf(">>"); }; private: char m_ch; }; //都实现了一个了,害怕实现第二个吗? 继续,干完早点回家 class outputHelloworld : public output { public: outputHelloworld(char* string) { strcpy_s(m_string, string); }; void firstoutput() { int length = strlen(m_string); for(int i=0; i<length; i++) { printf("%c", '-'); } printf("\n"); }; void secondoutput() { for(int i=0; i<5; i++) { printf("%s\n", "hello world"); } }; void thirdoutput() { //和first 输出一样,省点事情 firstoutput(); }; private: char m_string[20]; }; //万事俱备,只欠东风,调用吧 int _tmain(int argc, _TCHAR* argv[]) { output * poutput = new outputH('H'); poutput->printtoscreen(); delete poutput; printf("\n\n\n"); poutput = new outputHelloworld("Hello world"); poutput->printtoscreen(); delete poutput; getchar(); return 0; }
相关文章推荐
- 设计模式C++模板方法模式-实际处理交给子类
- java设计模式---Template Method模板方法---实际处理交给子类
- templete_method 模板方法模式
- 设计模式回顾-Template模式(实际处理交给子类)
- 设计模式(三)-模版模式(Template Pattern)——将具体处理交给子类
- 模板方法模式【Template Method Pattern 】
- 1.模板方法 Template Method
- 模板方法设计模式扩展(Hook Method)
- NSOperation使用系统提供子类的方法--处理复杂任务
- 【Android】-- 处理 android 方法总数超过 65536 . the number of method references in a .dex file exceed 64k的两种办法
- 子类对父类中虚方法的处理有重写(override)和覆盖(new)的区别
- .net调用别人的http页面,返回结果,url中有中文的处理,get和post两种方法
- iOS 开发 深入浅出Runtime运行时之方法动态处理(Dynamic Method Resolution)详解
- 模板方法模式 The Template Method Pattern
- 设计模式 - Template Method Pattern(模板方法模式)
- 设计模式19:Template Method Pattern (模板方法模式)
- 设计模式:模板方法模式-template method
- 设计模式之22 - 模板方法Template method
- nc55打模模板添加图章后保存失败的处理方法(增加字段长度)
- 模板方法模式Templet Method Pattern