抽象工厂模式 Abstract Factory

百度百科:抽象工厂模式是指当有多个抽象角色时,使用的一种工厂模式。抽象工厂模式可以向客户端提供一个接口,使客户端在不必指定产品的具体的情况下,创建多个产品族中的产品对象。根据LSP原则,任何接受父类型的地方,都应当能够接受子类型。因此,实际上系统所需要的,仅仅是类型与这些抽象产品角色相同的一些实例,而不是这些抽象产品的实例。换言之,也就是这些抽象产品的具体子类的实例。工厂类负责创建抽象产品的具体子类的实例。

//抽象工厂,对工厂抽象化,对同一类型工厂生成几个不同工厂

#include<iostream>
using namespace std;

class Fruit{
public:
    virtual void show() = 0;
};

class Apple:public Fruit{
public:
    void show(){
        cout<<"i am an apple"<<endl;
    }
};

class Pear:public Fruit{
public:
    void show(){
        cout<<"i am a pear"<<endl;
    }
};

class ShandongApple:public Apple{
public:
    void show(){
        cout<<"i am an apple from shandong"<<endl;
    }
};

class FujianApple:public Apple{
public:
    void show(){
        cout<<"i am an apple from fujian"<<endl;
    }
};

class ShandongPear:public Pear{
public:
    void show(){
        cout<<"i am a pear from shandong"<<endl;
    }
};

class FujianPear:public Pear{
public:
    void show(){
        cout<<"i am a pear from fujian"<<endl;
    }
};

class Factory{
public:
    virtual Fruit * getPear() = 0;
    virtual Fruit * getApple() = 0;
};

class ShandongFactory:public Factory{
public:
    Fruit * getPear(){
        return new ShandongPear();
    }
    Fruit * getApple(){
        return new ShandongApple();
    }
};

class FujianFactory:public Factory{
public:
    Fruit * getPear(){
        return new FujianPear();
    }
    Fruit * getApple(){
        return new FujianApple();
    }
};
int main(int argc, char* argv[])
{
    Factory * facshandong = new ShandongFactory();
    Fruit * psdapple = facshandong->getApple();
    Fruit * psdpear = facshandong->getPear();
    psdapple->show();
    psdpear->show();

    delete psdpear;
    delete psdapple;
    delete facshandong;

    Factory * facfujian = new FujianFactory();
    Fruit * pfjapple = facfujian->getApple();
    Fruit * pfjpear = facfujian->getPear();
    pfjapple->show();
    pfjpear->show();

    delete pfjpear;
    delete pfjapple;
    delete facfujian;
    return 0;
}

 

posted @ 2015-07-06 11:02  朽木可雕否  阅读(143)  评论(0编辑  收藏  举报