设计模式-抽象工厂模式

shienh 2020年01月20日 245次浏览

抽象工厂(AbstractFactory)模式的定义:是一种为访问类提供一个创建一组相关或相互依赖对象的接口,且访问类无须指定所要产品的具体类就能得到同族的不同等级的产品的模式结构。抽象工厂不满足开闭原则。

在实际需求中,一个工厂,不可能都只生产一种产品。还是以水果为例,苹果,香蕉是水果。但是中国香蕉和日本香蕉,中国苹果和日本苹果就不一样。这时候需要抽象出一个工厂,既可以生产香蕉,又可以生产苹果

​
#include <iostream>
using namespace std;


class AbstractApple{
public:
    virtual void ShowName()=0;
};


class AbstractBanana{
public:
    virtual void ShowName()=0;

};

class  ChinaApple:public AbstractApple{
public:
    virtual void ShowName(){
        cout<<"China Apple"<<endl;
    }
};

class  ChinaBanana:public AbstractBanana{
public:
    virtual void ShowName(){
        cout<<"China Banana"<<endl;
    }
};


class JapanApple:public AbstractApple{
public:
    virtual void ShowName(){
        cout<<"Japan Apple"<<endl;
    }
};

class JapanBanana:public AbstractBanana{
public:
    virtual void ShowName(){
        cout<<"Japan Banana"<<endl;
    }
};


class AbstractFactory{
public:
    virtual AbstractApple* CreateApple()=0;
    virtual AbstractBanana* CreateBanana()=0;
};

class ChinaFactory:public AbstractFactory
{
public:
    virtual AbstractApple* CreateApple(){
        return new ChinaApple;
    }
    virtual AbstractBanana* CreateBanana(){
        return  new ChinaBanana;
    }
};


class JapanFactory:public AbstractFactory
{
public:
    virtual AbstractApple* CreateApple(){
        return new JapanApple;
    }
    virtual AbstractBanana* CreateBanana(){
        return  new JapanBanana;
    }
};

int main(int argc, char *argv[])
{
    AbstractFactory* factory;
    AbstractApple* apple;
    AbstractBanana* banana;

    factory = new ChinaFactory;
    apple=factory->CreateApple();
    banana=factory->CreateBanana();
    apple->ShowName();
    banana->ShowName();
    delete apple;
    delete banana;
    delete factory;

    factory = new JapanFactory;
    apple=factory->CreateApple();
    banana=factory->CreateBanana();
    apple->ShowName();
    banana->ShowName();
    delete apple;
    delete banana;
    delete factory;

    return 0;
}

​