设计模式:template method模式

思想:在父类中定义处理流程的框架,在子类中实现具体的处理方法

优点:在父类中定义处理的算法,无需在每个子类中重复编写

继承关系图:

例子:

//接口定义
class Parent
{
public:
	virtual void open() = 0;     //需要子类实现
	virtual void print() = 0;    //需要子类实现
	virtual void close() = 0;    //需要子类实现
	virtual void work()          //模板方法,定义处理的流程框架
	{
		open();
		for(int i=0; i<5; i++)
		{
			print();
		}
		close();
	}
};
//子类实现具体的方法
class Child: public Parent
{
public:
	void open() //子类具体实现
	{
		cout << "----------------------" << endl;
	}
	
	void print() //子类具体实现
	{
		cout << " Good Good Good Good" << endl;
	}
	
	void close() //子类具体实现
	{
		cout << "----------------------" << endl;
	}
};
int main() 
{
	Parent* p = new Child();
	p->work();
	return 0;
}

 

posted @ 2019-08-30 08:28  Yong_无止境  阅读(578)  评论(0编辑  收藏  举报