设计模式--抽象工厂模式


抽象工厂模式的简介

抽象工厂模式中的具体工厂类中,定义了多个创建产品的方法,可以创建同一个工厂的不同产品,比如奥迪工厂可以创造Audi汽车,也可以生产轮胎,车灯等产品。把这些产品的生产都集中到一个具体产品的类中。就避免了创建多个类。
如果使用工厂模式,想要生产汽车,车灯,轮胎需要创建六个类。奥迪汽车工厂类,奥迪车灯工厂类,奥迪轮胎工厂类,奥迪汽车产品类,奥迪车灯产品类,奥迪轮胎产品类。但是使用抽象工厂就只用创建一个工厂类(奥迪工厂类)就可以了,在这个工厂类中分别用三个静态函数实现汽车,轮胎,车灯的生产。
在这里插入图片描述
在抽象工厂模式结构图中包含如下几个角色:

AbstractFactory(抽象工厂):它声明了一组用于创建一族产品的方法,每一个方法对应一种产品。

ConcreteFactory(具体工厂):它实现了在抽象工厂中声明的创建产品的方法,生成一组具体产品,这些产品构成了一个产品族,每一个产品都位于某个产品等级结构中。

AbstractProduct(抽象产品):它为每种产品声明接口,在抽象产品中声明了产品所具有的业务方法。

ConcreteProduct(具体产品):它定义具体工厂生产的具体产品对象,实现抽象产品接口中声明的业务方法。
代码展示

//抽象产品类
class Car
{public:
	Car(){}
	virtual ~Car(){}
	virtual void show() = 0;
};
//具体产品类
class AudiCar :public Car
{
public:
	AudiCar() { cout << "construct Audi car" << endl; }
	~AudiCar() { cout << "destory Audi car" << endl; }
	void show() { cout << "this is a Audi car" << endl; }
};
class BenzCar :public Car
{public:
	BenzCar() { cout << "construct Benz car" << endl; }
	~BenzCar() { cout << "destory Benz car" << endl; }
	void show() { cout << "this is a Benz car" << endl; }
};

//抽象产品类
class tyre
{
public:
	tyre() {}
	virtual ~tyre() {}
	virtual void show() = 0;
};
//具体产品类
class AudiTyre :public tyre
{
public:
	AudiTyre() { cout << "construct Audi tyre" << endl; }
	~AudiTyre(){ cout << "destory Audi tyre" << endl; }
	void show(){ cout << "this is a Audi tyre" << endl; }
};
class BenzType :public tyre
{
public:
	BenzType() { cout << "construct Benz tyre" << endl; }
	~BenzType() { cout << "destory Benz tyre" << endl; }
	void show() { cout << "this is a Benz tyre" << endl; }
};
//抽象工厂
class Abstructfactory
{
public:
	Abstructfactory(){}
	virtual ~Abstructfactory(){}
	virtual Car* getcar() = 0;
	virtual tyre* getTyre() = 0;
};
//具体工厂
class AudiFactory:public Abstructfactory
{
public:
	AudiFactory(){}
	~AudiFactory(){}
	Car* getcar()
	{
		return new AudiCar();
	}
	tyre* getTyre()
	{
		return new AudiTyre();
	}
};
class BenzFactory :public Abstructfactory
{
public:
	BenzFactory() {}
	~BenzFactory() {}
	Car* getcar()
	{
		return new BenzCar();
	}
	tyre* getTyre()
	{
		return new BenzType();
	}
};
int main()
{
	unique_ptr<Abstructfactory> Adfac(new AudiFactory);
	unique_ptr<Car> Adcar(Adfac->getcar());
	unique_ptr<tyre> Adtype(Adfac->getTyre());
	
	Adcar->show();
	Adtype->show();

	unique_ptr<Abstructfactory> bzfac(new BenzFactory);
	unique_ptr<Car> bzcar(bzfac->getcar());
	unique_ptr<tyre> bztype(bzfac->getTyre());

	bzcar->show();
	bztype->show();
	return 0;

}

结果
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值