[C++]模板方法模式

模板方法模式,定义一个操作中的算法骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。

C++代码如下:

// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// 参考大话设计模式 - 模板方法模式

#include <iostream>

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} }
#endif

using namespace std;

// 基类:提供按照某个流程的具体实现方法。
//       流程内的具体步骤,由子类可定制。
class AbstractClass {
public:
	virtual void doSomething() = 0;
	virtual void doOtherthing() = 0;

public:
	void someDoIt() {
		doSomething();
		doOtherthing();
		cout << "do job" << endl;
	}
};

// 子类仅实现自己定制的具体步骤。步骤组合后的流程,由基类实现。
class aBoy : public AbstractClass {
public:
  void doSomething() {
		cout << "A boy do something and ";
	}

	void doOtherthing() {
		cout << " do otherthing about :";
	}
};

// 子类仅实现自己定制的具体步骤。步骤组合后的流程,由基类实现。
class aGirl : public AbstractClass {
public:
	void doSomething() {
		cout << "A girl do something and ";
	}

	void doOtherthing() {
		cout << "do otherthing about :";
	}
};

int main()
{
	aBoy* aboy = new aBoy();
	aboy->someDoIt();
	SAFE_DELETE(aboy);

	aGirl* agirl = new aGirl();
	agirl->someDoIt();
	SAFE_DELETE(agirl);

	return 0;
}


github源码路径:https://github.com/dangwei-90/Design-Mode

持续更新中

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值