大話設計模式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;
}

參考資料

程傑老師的《大話設計模式》
模板模式|菜鳥編程

如果對你有幫助的話,記得點贊收藏,如果有什麼遺漏的或者有什麼體會,請在評論告訴我,好東西記得分享 ^ _ ^

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