您的位置:首页 > 其它

模板方法 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: