简单工厂模式

用户提供一个标签,工厂通过一个函数来判断。比如用户提供一个苹果,水果工厂就得根据水果生成器(函数)来创建一个苹果。这些水果的类在外面是已经写好了的。

这个水果生成器直接返回一个水果种类的指针。例子如下。

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>

using namespace std;

//抽象的水果类
class Fruit
{
public:
    virtual void getName() = 0;
};

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

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

//添加一个新产品 鸭梨
class Pear :public Fruit
{
public:
    virtual void getName() {
        cout << "我是鸭梨" << endl;
    }
};

//工厂
class Factory {
public:
    //水果生产器
    Fruit * createFruit(string kind) {
        Fruit *fruit = NULL;

        if (kind == "apple") {
            fruit =  new Apple;
        }
        else if(kind == "banana"){
            fruit =  new Banana;
        }
        //添加一个鸭梨   修改了工厂的方法, 违背了开闭原则
        else if (kind == "pear") {
            fruit = new Pear;
        }
        return fruit;
    }
};

int main(void)
{
    //人们是跟工厂打交道
    Factory *factory = new Factory; //创建一个工厂
    //给我来一个苹果
    Fruit *apple = factory->createFruit("apple");

    apple->getName();


    Fruit *banana = factory->createFruit("banana");
    banana->getName();

    Fruit *pear = factory->createFruit("pear");

    delete apple;
    delete banana;
    delete factory;

    
    return 0;
}

 

posted @ 2020-03-22 09:19  撑雨伞的小男孩  阅读(138)  评论(0编辑  收藏  举报