Henkk

导航

设计模式学习之----工厂模式

简单工厂模式适用场景:
  • 工厂类负责创建的对象比较少:由于创建的对象较少,不会造成工厂方法中的业务逻辑太过复杂。
  • 客户端只知道传入工厂类的参数,对于如何创建对象不关心:客户端既不需要关心创建细节,甚至连类名都不需要记住,只需要知道类型所对应的参数

  工厂方法:工厂作为基类,具体的类集成工厂实现自己的创造方法。(多态工厂(Polymorphic Factory)模式)

     缺点:1. 需要编写新的具体产品类,而且还要提供与之对应的具体工厂类

          2. 一个具体工厂只能生产一种产品

 抽象工厂模式:主要解决一个工厂只能生产一种产品的问题,它可以生产多个产品。

#include <iostream>
#include <string>

using namespace std;
//简单工厂模式-----不符合开闭原则,不是标准的设计模式
// 工厂生产接口,返回想要的对象,该对象有共同的基类继承;
// 添加新类型的方法: 1.添加新类型的类 2.改写工厂的创建函数
class Fruit
{
public:
    virtual void getFruit()
    {
        cout << "我是水果" << endl;
    }
};

class Apple : public Fruit
{
public:
    virtual void getFruit()
    {
        cout << "我是苹果....." << endl;
    }
};

class Banana : public Fruit
{
public:
    virtual void getFruit()
    {
        cout << "I am banana....." << endl;
    }
};

class Factory
{
public:
    Fruit *create(char *p)
    {
        if (strcmp(p, "banana") == 0)
        {
            return new Banana;
        }
        else if (strcmp(p, "apple") == 0)
        {
            return new Apple;
        }
        else
        {
            ;
        }
    }
};

//工厂模式
//实现了面向抽象类编程
//添加新的类型步骤:1.添加创建新对类型的工厂类 2.添加新对象类
class AbFactory
{
public:
    virtual Fruit* CreatProduct() = 0;
};

class AppleFactory : public AbFactory
{
public:
    virtual Fruit* CreatProduct()
    {
        return new Apple;
    }
};

class BananaFactory : public AbFactory
{
public:
    virtual Fruit* CreatProduct()
    {
        return new Banana;
    }
};

int main()
{
    AbFactory *factory = nullptr; //抽象类
    Fruit     *fruit = nullptr;  //抽象类

    //生产香蕉
    factory = new BananaFactory;
    fruit = factory->CreatProduct();
    fruit->getFruit();

    delete factory;
    delete fruit;

    return system("pause");
}

 

posted on 2020-05-22 11:36  Henkk  阅读(118)  评论(0编辑  收藏  举报