设计模式-模板方法模式

模板方法模式TemplateMethod):

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


1.模板方法模式是通过把不变行为搬移到超类,去除子类中的重复代码来体现它的优势。
2.模板方法模式就是提供了一个很好的代码复用平台。
3.当不变的和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现。我们通过模板方法模式把这些行为搬移到单一的地方,这样就帮助子类摆脱重复的不变行为的纠缠。

接下来简单实现下上面的UML所表示的内容。
模板方法实现代码

#pragma once

#include <string>
#include <iostream>
using namespace std;

class CTemplateInterface
{
public:
	virtual void PrimitiveOperation1() = 0;
	virtual void PrimitiveOperation2() = 0;
	void DoHapplyThings()
	{
		PrimitiveOperation1();
		PrimitiveOperation2();
		cout<<"Over"<<endl;
	}
};

class CConcreteClassA : public CTemplateInterface
{
public:
	void PrimitiveOperation1()
	{
		cout<<"A:1"<<endl;
	}
	void PrimitiveOperation2()
	{
		cout<<"A:2"<<endl;
	}
};

class CConcreteClassB : public CTemplateInterface
{
public:
	void PrimitiveOperation1()
	{
		cout<<"B:1"<<endl;
	}
	void PrimitiveOperation2()
	{
		cout<<"B:2"<<endl;
	}
};

客户端调用代码
#include "stdafx.h"
#include "TemplateMode.h"
#include <windows.h>

using namespace std;

int main()
{
	CTemplateInterface *cTemplate = NULL;
	cTemplate = new CConcreteClassA();
	cTemplate->DoHapplyThings();
	delete cTemplate;

	cTemplate = new CConcreteClassB();
	cTemplate->DoHapplyThings();
	delete cTemplate;

	return 0;
}
执行结果


    比较简单,就不多说了!


原文地址:https://www.cnblogs.com/csnd/p/12062349.html