首页 > 其他 > 详细

创建型模式 简单工厂模式

时间:2017-11-02 20:52:19      阅读:211      评论:0      收藏:0      [点我收藏+]

创建型模式 简单工厂模式

 

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

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


#include <iostream>

class Fruit
{
public:
    virtual void getFruit() = 0;
    ~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;
            return 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;
}

 

创建型模式 简单工厂模式

原文:http://www.cnblogs.com/lsgxeva/p/7773995.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!