DesignPatterns_TemplateMethod

////////////////////////////////////////////////////////////////////////////
// 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章