创建型模式 简单工厂模式

创建型模式 简单工厂模式

 

 

/**
 * 创建型模式 简单工厂模式
 * 简单工厂模式属于类的创建型模式,又叫做静态工厂方法模式。通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
 *
 * 1.工厂(Creator)角色
 * 简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类可以被外界直接调用,创建所需的产品对象。
 * 2.抽象(Product)角色
 * 简单工厂模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。
 * 3.具体产品(Concrete Product)角色
 * 简单工厂模式所创建的具体实例对象
 *
 */

//思想: 核心思想是用一个工厂,来根据输入的条件产生不同的类,然后根据不同类的virtual函数得到不同的结果。 
//元素分析:  
//抽象产品类:水果类  
//具体的水果了:香蕉类、苹果类、梨子 
//优点 适用于不同情况创建不同的类时 
//缺点 客户端必须要知道基类和工厂类,耦合性差 增加一个产品,需要修改工厂类 


#include <iostream>

class Fruit
{
public:
    virtual void getFruit() = 0;
    virtual ~Fruit() {}
};

class Banana: public Fruit
{
public:
    virtual void getFruit() override
    {
        std::cout << "我是香蕉" << std::endl;
    }
};

class Pear: public Fruit
{
public:
    virtual void getFruit() override
    {
        std::cout << "我是梨子" << std::endl;
    }
};

class Factory
{
public:
    static Fruit * Create(char * name)
    {
        Fruit *tmp = nullptr;
        if (strcmp(name, "banana") == 0)
        {
            tmp = new Banana();
        } 
        else if (strcmp(name, "pear") == 0)
        {
            tmp = new Pear();
        }
        else
        {
            std::cout << "不支持" << std::endl;
            tmp = nullptr;
        }
        return tmp;
    }
};

void mytest()
{
    Fruit *fruit = nullptr;

    fruit = Factory::Create("banana");
    if (fruit == nullptr)
    {
        std::cout << "创建香蕉失败" << std::endl;
    }
    fruit->getFruit();
    delete fruit;
    fruit = nullptr;

    fruit = Factory::Create("banana");
    if (fruit == nullptr)
    {
        std::cout << "创建梨子失败" << std::endl;
    }
    fruit->getFruit();
    delete fruit;
    fruit = nullptr;

    return;
}


int main()
{
    mytest();

    system("pause");
    return 0;
}

 

posted @ 2017-11-02 19:46  lsgxeva  阅读(255)  评论(0编辑  收藏  举报