DesignPatterns_TemplateMethod

本文介绍模板方法设计模式,定义了算法骨架,将某些步骤延迟到子类实现。允许子类重新定义算法步骤而不改变结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

////////////////////////////////////////////////////////////////////////////
// Template Method pattern
// - Define the skeleton of an algorithm in an operation, deferring some steps
//   to subclasses. Template Method lets subclasses redefine certain steps of an 
//   algorithm without changing the algorithm structure.
//
// Author     : ZAsia
// Date       : 15/05/17
// Warning    : In practice, declaration and implementation should
//              be separated(.h and .cpp).
//////////////////////////////////////////////////////////////////////////////
#include 
using namespace std;

// AbstractClass
// - defines abstract primitive operations that concrete subclasses define
//   to implement steps of an algorithm.
// - implements a template method defining the skeleton of an algorithm. The
//   template method calls primitive operations as well as operaions defined
//   in AbstractClass or those of other object.
class AbstractClass
{
public:
	void TemplateMethod()
	{
		PrimitiveOperation1();
		PrimitiveOperation2();
	}
protected:
	virtual void PrimitiveOperation1() = 0;
	virtual void PrimitiveOperation2() = 0;
};

// ConcreteClass
// - implements the primitive operations to carry out subclass-specific steps
//   of the algorithm.
class ConcreteClass : public AbstractClass
{
protected:
	virtual void PrimitiveOperation1()
	{
		cout << "ConcreteClass::PrimitiveOperation1" << endl;
	}
	virtual void PrimitiveOperation2()
	{
		cout << "ConcreteClass::PrimitiveOperation2" << endl;
	}
};

// Collaborations
// - ConcreteClass relies on AbstractClass to implement the invariant steps of
//   the algorithm.
int main()
{
	// if "new (nothrow)"allocation fails, new returns a nullptr 
	AbstractClass *pAbstractClass = new(nothrow) ConcreteClass();
	if (pAbstractClass)
	{
		pAbstractClass->TemplateMethod();
		// ... 
		delete pAbstractClass;
		pAbstractClass = nullptr;
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值