【学习总结】简单工厂

模式定义

1.1 简单工厂模式(Simple Factory Pattern)

实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(继承自一个父类或接口)的实例。

1.1.1 模式结构
角色说明
Factory(工厂)负责创建所有具体产品类的实例
Product(抽象产品)负责描述所有实例所共有的公共接口
ConcreteProduct (具体产品)继承自抽象产品角色,返回的都是某一具体产品
1.1.2 模式优缺点

优点:
客户端与具体实现类解耦;
不用考虑对象的创建过程。

缺点:
工厂类集中了所有产品创建逻辑,一旦不能正常工作,整个系统都要受到影响;
系统类个数的递增,增加了系统的复杂度和理解难度;
系统扩展困难,不利于扩展和维护;
不符合开闭原则。

1.1.3 模式适用环境

工厂类创建的对象比较少,且不易变更;
客户端需要知道传入工厂类的参数,不需要关心如何创建对象。

1.1.4 模式代码

Product

//InterfaceTV.h
class InterfaceTV
{
public:
	virtual void play() = 0;
};

ConcreteProduct
HaierTV

//HaierTV.h
#include "InterfaceTV.h"
class HaierTV :public InterfaceTV
{
public:
	virtual void play();
};
//HaierTV.cpp
#include <iostream>
#include "HaierTV.h"

using namespace std;

void HaierTV::play()
{
	cout << "Haier TV is playig..." << endl;
}

HisenseTV

//HisenseTV.h
#include "InterfaceTV.h"
class HisenseTV:public InterfaceTV
{
public:
	virtual void play();
};
//HisenseTV.cpp
#include <iostream>
#include "HisenseTV.h"
using namespace std;

void HisenseTV::play()
{
	cout << "Hisense TV is playig..." << endl;
}

Factory

#include "InterfaceTV.h"
#include "HisenseTV.h"
#include "HaierTV.h"

class TVFactory
{
public:
	InterfaceTV * MakeTV(int type);
};
#include "TVFactory.h"

InterfaceTV * TVFactory::MakeTV(int type)
{
	switch (type)
	{
	case 1:
		return new HaierTV;
	case 2:
		return new HisenseTV;

	default:
		return nullptr;
	}
}

Use

#include <iostream>
#include <stdio.h>

#include "InterfaceTV.h"
#include "TVFactory.h"

using namespace std;

void ShowResult(InterfaceTV& IntTV);

int main(int argc, char *argv[])
{
	int type = 0;
	cout << "Input an type:";
	cin >> type;
	TVFactory Tvf;
	InterfaceTV *intTV = Tvf.MakeTV(type);
	if (intTV == NULL)
	{
		return -1;
	}
	ShowResult(*intTV);
	delete intTV;
	cout << "Press any key to continue" << endl;
	cin.get();
	cin.get();
	return 0;

}

void ShowResult(InterfaceTV& IntTV)
{
	IntTV.play();
}

运行结果:
Haier
Hisense

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值