抽象工厂模式

1.抽象工厂模式与工厂模式

工厂模式中的工厂和产品都有自己的一个抽象基类,每个工厂各施其职,只能生产一种产品。而抽象工厂模式可以生产一个产品族,其原因是其抽象基类中包含多个纯虚函数的接口,而工厂模式的抽象基类只有一个纯虚函数的接口。

2.具体例子

#include<iostream>
using namespace std;
class Fruit
{
public:
    virtual void sayName() = 0;
};

class Factory
{
public:
    virtual Fruit * CreateBanana() = 0;
    virtual Fruit * CreateApple() = 0;
};

class SouthApple :public Fruit
{
public:
    virtual void sayName()
    {
        cout << "I'm southApple" << endl;
    }
};

class NorthApple :public Fruit
{
public:
    virtual void sayName()
    {
        cout << "I'm northApple" << endl;
    }
};
class SouthBanana :public Fruit
{
public:
    virtual void sayName()
    {
        cout << "I'm southBanana" << endl;
    }
};

class NorthBanana :public Fruit
{
public:
    virtual void sayName()
    {
        cout << "I'm northBanana" << endl;
    }
};

class SouthFactory:public Factory
{
public:
    virtual Fruit * CreateBanana()
    {
        return new SouthBanana;
    }
    virtual Fruit * CreateApple()
    {
        return new SouthApple;
    }
};

class NorthFactory :public Factory
{
public:
    virtual Fruit * CreateBanana()
    {
        return new NorthBanana;
    }
    virtual Fruit * CreateApple()
    {
        return new NorthApple;
    }
};

int main()
{
    Factory * fa = nullptr;
    Fruit * fr = nullptr;

    fa = new SouthFactory;
    fr = fa->CreateApple();
    fr->sayName();
    delete fr;
    fr = fa->CreateBanana();
    fr->sayName();
    delete fr;
    /*-------------------------------------*/
    fa = new NorthFactory;
    fr = fa->CreateApple();
    fr->sayName();
    delete fr;
    fr = fa->CreateBanana();
    fr->sayName();
    delete fr;
    system("pause");

    return 0;
}

 

posted @ 2018-11-12 21:18  我寒流  阅读(171)  评论(0编辑  收藏  举报