模板方法 Templete Method 实际的处理交给子类,让别人去干吧。

// 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值