设计模式(二):工厂模式

本文介绍了工厂模式的三种类型:简单工厂模式、工厂方法模式和抽象工厂模式。简单工厂模式通过一个公共接口创建对象,但增加新产品时需修改工厂类。工厂方法模式为每种产品提供独立工厂,降低了耦合。抽象工厂模式则适用于生产多种类型产品的情况。虽然工厂模式存在扩展性问题,但在实际应用中仍广泛使用。
摘要由CSDN通过智能技术生成

前言

工厂模式提供了一种创建对象的最佳方式,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。工厂模式分为简单工厂模式、工厂方法模式和抽象工厂模式,c++工厂模式主要利用了多态的特性,有关多态的内容可以参考c++多态

简单工厂模式

简单工厂模式包括三个组件:

  • 工厂类:用于创建一个指定具体实例对象。
  • 具体产品类:工厂模式创建的对象。
  • 抽象产品类:具体产品继承的父类或实现的接口。

可以通过一个实例来了解简单工厂模式,假设我们需要通过工厂模式生产衣服,工厂类定义为clothesFactor,具体产品定义为adidasClothes和nikeClothes,抽象产品类定义为clothes。
为了方便展示,在抽象产品类中定义print()接口:

//clothes abstract
class clothes{
   
public:
	virtual void print() = 0;     //纯虚函数,需要具体产品实现
	virtual ~clothes() {
   };    //虚析构函数避免内存泄漏
}

具体产品类继承抽象产品类,实现响应接口:

//all kinds of clothes class
class adidasClothes : public clothes{
   
public:
	void print(){
   
		std::cout << "it is adidas clothes" << std::endl;
	}
}

class nikeClothes : public clothes{
   
public:
	void print(){
   
		std::cout << "it is nike clothes" << std::endl;
	}
}

最后是工厂类的实现,工厂类只需要生产出具体产品即可:

//clothes factory
enum clothes_type{
   
	adidas,
	nike
};

class clothesFactory{
   
public:
	clothes* createClothes(clothes_type type){
   
		switch (type){
   
        case nike:
            return new nikeClothes();
            break;
        case adidas:
            return new adidasClothes();
            break;
        default:
            return nullptr;
            break;
        }
	}
}

最后贴出完整代码,并通过int main()函数中的代码测试创建简单工厂模式:

#include <iostream>
//衣服类型
enum clothes_type{
   
	adidas,
	nike
};
//抽象产品
class clothes{
   
public:
	virtual void print() = 0;     //纯虚函数,需要具体产品实现
	virtual ~clothes() {
   };    //虚析构函数避免内存泄漏
};
//具体产品adidas
class adidasClothes : public clothes{
   
public:
	void print(){
   
		std::cout << "it is adidas clothes" << std::endl;
	}
};
//具体产品nike
class nikeClothes : public clothes{
   
public:
	void print(){
   
		std::cout << "it is nike clothes" << std::endl;
	}
};
//工厂
class clothesFactory{
   
public:
	clothes* createClothes(clothes_type type)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值