Linuxkiss
    首页 Linux C/C++ C++面试 Qt答疑 Qml中文手册 Qt CMake Python 工具
Linuxkiss
www.linuxkiss.com 你可以精通一门IT技术
  1. 首页
  2. C++设计模式
  3. 正文

简单工厂模式_工厂模式_设计模式

2020年11月30日 20点热度 0人点赞

工厂模式
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。工厂模式作为一种创建模式,一般在创建复杂对象时,考虑使用;在创建简单对象时,建议直接new完成一个实例对象的创建。

简单工厂模式
特点:在工厂类中做判断,从而创造相应的产品,当增加新产品时,需要修改工厂类。使用简单工厂模式,我们只需要知道具体的产品型号就可以创建一个产品。

缺点:工厂类集中了所有产品类的创建逻辑,如果产品量较大,会使得工厂类变的非常臃肿。

代码理解

#include <iostream>
​
using namespace std;
​
//定义产品类型信息
typedef enum
{
    Lenovo,
    Asus,
    Apple
}Computer_Type;
​
//抽象产品类
class Computer
{
public:
    virtual const string& type() = 0;
};
​
//具体的产品类
class Lenovo : public Computer
{
public:
    Lenovo():Computer(),m_strType("Lenovo")
    {
    }
​
    const string& type() override
    {
        cout << m_strType.data() << endl;
        return m_strType;
    }
private:
    string m_strType;
};
​
//具体的产品类
class Apple : public Computer
{
public:
    Apple():Computer(),m_strType("Apple")
    {
    }
    const string& type() override
    {
        cout << m_strType.data() << endl;
        return m_strType;
    }
​
private:
    string m_strType;
};
​
//工厂类
class ComputerFactory
{
public:
    //根据产品信息创建具体的产品类实例,返回一个抽象产品类
    Computer* createComputer(Computer_Type type)
    {
        switch(type)
        {
        case Lenovo:
            return new Lenovo();
        case Apple:
            return new Apple();
        default:
            return nullptr;
        }
    }
};
​
​
int main()
{
    ComputerFactory* factory = new ComputerFactory();
    Computer* Lenovo = factory->createComputer(Lenovo);
    Lenovo->type();
    Computer* Apple = factory->createComputer(Apple);
    Apple->type();
​
    delete Lenovo;
    Lenovo = nullptr;
    delete Apple;
    Apple = nullptr;
    delete factory;
    factory = nullptr;
​
    return 0;
}

 

标签: 工厂模式 简单工厂模式 设计模式
最后更新:2020年11月30日

Leo

保持饥渴的专注,追求最佳的品质

点赞
下一篇 >
关注公众号

日历
2021年4月
一 二 三 四 五 六 日
« 2月    
 1234
567891011
12131415161718
19202122232425
2627282930  
最新 热点 随机
最新 热点 随机
windows中出现"无法解析的外部符号"到底是什么原因 Qt5中lambda表达式用法,非常实用 warning: class 'InterFace' defines a non-default destructor but does not define a copy constructor, a copy assignment operator, a move constructor or a move assignment operator 无法解析的外部符号 "public: static struct QMetaObject const Windows下Qt代码出现的错误总结 QT Creator如何在创建项目的时候,头文件和cpp文件的首字母默认大写
希尔排序【C语言】 Qt5中CMake命令qt5_add_binary_resources QML类型系统(The QML Type System) opencv系列17--Sobel算子,Scharr算子 [ api:Sobel,api:Scharr ] opencv系列21--霍夫圆变换 [ api:HoughCircles ] QML语法--qml中的注释(Comments)
标签聚合
openCv qmake Linux qml中文文档 Qt qml中文手册 C++ C/C++面试

COPYRIGHT © 2020 Linuxkiss. ALL RIGHTS RESERVED.