设计模式之简单工厂

一、适用场景

1.、工厂类负责创建的对象比较少,由于创建的对象较少,不会造成的业务逻辑太过复杂
2.、客户端只知道传入工厂类的参数,对于如何创建对象并不关心

二、示例代码

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

//抽象水果
class AbstractFruit{
public:
    virtual void ShowName() = 0;
};

//苹果
class Apple : public AbstractFruit{
public:
    virtual void ShowName(){
	cout << "苹果!" << endl;
    }
};

//香蕉
class Banana : public AbstractFruit{
public:
    virtual void ShowName(){
        cout << "香蕉!" << endl;
    }
};



//水果工厂
class FruitFactory
{
public:
    AbstractFruit* CreateFruit(string name)
    {
	 if (name == "apple")
         {
              return new Apple;
	 }
	 else if (name == "banana")
         {
	      return new Banana;
	 }
	 else
         {
	      return NULL;
	 }
    }
};

void test(void)
{
    FruitFactory * factory = new FruitFactory;
    AbstractFruit * fruit = factory->CreateFruit("apple");
    fruit->ShowName();
    delete fruit;

    fruit = factory->CreateFruit("banana");
    fruit->ShowName();
    delete fruit;

    delete factory;
}




int main(void)
{
    test();
    return 0;
}

 

上一篇:因为生娃在家待业一年半的宝妈,如何实现逆袭?王者归来涨薪9k


下一篇:selenium + firefox/chrome/phantomjs登陆之模拟点击