大话设计模式C++版本-07-模板方法模式

概述

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

  1. 封装不变部分,扩展可变部分
  2. 提取公共代码,便于维护
  3. 行为由父类控制,子类实现

缺点:每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。

使用场景

  1. 一个类有大部分的功能是一直不需要改变的
  2. 但有少部分的功能需要依据不同情况改变

例子:小学时,学生对着黑板抄习题时,每个人抄的题目是不变的,但每个人的答案是不同的,按照模板方法模式,可以把题目提取到父类来实现,而每个子类实现各自的答案。

一般步骤

  1. 写一个父类实现公共代码,把可变的用虚方法实现;
    class TestPaper // 试卷类
    {
    public:
    	void TestQuestion1()
    	{
    		cout << "杨过得到,后来给了郭靖 a.球;b.金;c.碳" << endl;
    		cout << "答案:" <<  Answer1() << endl;
    	}
    	// ...其他公共代码	
    	virtual string Answer1()
    	{
    		return "";
    	}
    	// ...其他可变代码
    };
    
  2. 写不同条件下的子类,继承父类,并实现可变代码;
    class TestPaperA : public TestPaper //A抄的试卷,实现了自己的答案
    {
    public:
    	string Answer1()
    	{
    		return "b";
    	}
    	//  ...
    };
    
    class TestPaperB : public TestPaper //B抄的试卷,实现了自己的答案
    {
    public:
    	string Answer1()
    	{
    		return "c";
    	}
    	// ...
    };
    

具体实例完整代码

#include <iostream>
#include <string>

using namespace std;

class TestPaper // 试卷类
{
public:
	void TestQuestion1()
	{
		cout << "杨过得到,后来给了郭靖 a.球;b.金;c.碳" << endl;
		cout << "答案:" <<  Answer1() << endl;
	}
	
	void TestQuestion2()
	{
		cout << "杨过、程英、陆无双 a.害;b.绝;c.平;d.化" << endl;
		cout << "答案:" <<  Answer2() << endl;
	}
	
	void TestQuestion3()
	{
		cout << "蓝凤凰 a.林;b.牛;c.酸;奶" << endl;
		cout << "答案:" <<  Answer3() << endl;
	}
	
	virtual string Answer1()
	{
		return "";
	}
	
	virtual string Answer2()
	{
		return "";
	}
	
	virtual string Answer3()
	{
		return "";
	}
};

class TestPaperA : public TestPaper //A抄的试卷,实现了自己的答案
{
public:
	string Answer1()
	{
		return "b";
	}
	
	string Answer2()
	{
		return "c";
	}
	
	string Answer3()
	{
		return "a";
	}
};

class TestPaperB : public TestPaper //B抄的试卷,实现了自己的答案
{
public:
	string Answer1()
	{
		return "c";
	}
	
	string Answer2()
	{
		return "a";
	}
	
	string Answer3()
	{
		return "a";
	}
};

int main()
{
	cout << "studentA的试卷" << endl;
	TestPaper *studentA = new TestPaperA();
	studentA->TestQuestion1();
	studentA->TestQuestion2();
	studentA->TestQuestion3();
	
	cout << endl;
	
	cout << "studentB的试卷" << endl;
	TestPaper *studentB = new TestPaperB();
	studentB->TestQuestion1();
	studentB->TestQuestion2();
	studentB->TestQuestion3();
	
	return 0;
}

参考资料

程杰老师的《大话设计模式》
模板模式|菜鸟编程

如果对你有帮助的话,记得点赞收藏,如果有什么遗漏的或者有什么体会,请在评论告诉我,好东西记得分享 ^ _ ^

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章