设计模式之模板模式-一个模子刻出来的!

一、模板模式的概念

模板模式属于行为型模式,在一个抽象父类中定义和规定了子类共同的方法,它的各个子类继承这个父类,并根据各自的需要重写抽象类中的方法。

二、模板模式使用场景

1、多个子类有共同的方法和相同的逻辑时,可以使用模板模式。
2、一些重要的和复杂的方法,可以使用模板模式。

三、模板模式构建方法

1、抽象父类

抽象父类给子类提供统一的共同接口和方法。

2、具体实现类

具体实现类继承抽象父类,用于实现抽象父类中的共同接口和方法。

四、模板模式的示例

// TemplatePattern.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>

using namespace std;

// 模板父类-制造手机
class ProductPhone
{
public:
	virtual void makeScreen() = 0;
	virtual void makeChip() = 0;
	virtual void makeBattery() = 0;
	
	void makePhone()
	{
		makeScreen();
		makeChip();
		makeBattery();
	}
};

// 模板子类-手机厂商们使用的各种零件开启“私人订制”模式
class ProductHuaWeiPhone : public ProductPhone
{
public:
	void makeScreen()
	{
		cout << "make a screen for HuaWei phone." << endl;
	}

	void makeChip()
	{
		cout << "make a chip for HuaWei phone." << endl;
	}

	void makeBattery()
	{
		cout << "make a Batttery for HuaWei phone." << endl;
	}
};

class ProductXiaoMiPhone : public ProductPhone
{
public:
	void makeScreen()
	{
		cout << "make a screen for XiaoMi phone." << endl;
	}

	void makeChip()
	{
		cout << "make a chip for XiaoMi phone." << endl;
	}

	void makeBattery()
	{
		cout << "make a Batttery for XiaoMi phone." << endl;
	}
};

class ProductOPPOPhone : public ProductPhone
{
public:
	void makeScreen()
	{
		cout << "make a screen for OPPO phone." << endl;
	}

	void makeChip()
	{
		cout << "make a chip for OPPO phone." << endl;
	}

	void makeBattery()
	{
		cout << "make a Batttery for OPPO phone." << endl;
	}
};

#define DELETE_PTR(p) {if(p!=nullptr){delete (p); (p)=nullptr;}}

int main()
	cout << "-----------------模板模式--------------------" << endl;
	cout << "---------制造华为手机-----------" << endl;
	ProductPhone *pHuaWeiPhone = new ProductHuaWeiPhone;
	pHuaWeiPhone->makePhone();

	cout << "---------制造小米手机-----------" << endl;
	ProductPhone *pXiaoMiPhone = new ProductXiaoMiPhone;
	pXiaoMiPhone->makePhone();

	cout << "---------制造OPPO手机-----------" << endl;
	ProductPhone *pOPPOPhone = new ProductOPPOPhone;
	pOPPOPhone->makePhone();

	DELETE_PTR(pHuaWeiPhone);
	DELETE_PTR(pXiaoMiPhone);
	DELETE_PTR(pOPPOPhone);

    std::cout << "Hello World!\n";
	getchar();
}

运行结果:
在这里插入图片描述

五、模板模式的优缺点

优点:

1、行为有父类控制,有子类去具体的实现。
2、封装相同的方法,提取公共的代码,便于维护与扩展。

缺点:

1、每一个不同的方法都需要一个子类来实现,导致类的个数增加,系统的体积不断扩大。

能力有限,如有错误,多多指教。。。

发布了157 篇原创文章 · 获赞 135 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/toby54king/article/details/104486720