美文网首页
抽象工厂模式

抽象工厂模式

作者: 大啸 | 来源:发表于2019-03-24 14:58 被阅读0次

    #include <iostream>

    using namespace std;

    //形状抽象类

    class Shape {

    public:

    virtual void Draw() = 0;

    };

    class Rect : public Shape {

    public:

    void Draw() {

    cout << "正方形" << endl;

    }

    };

    class Circ : public Shape {

    public:

    void Draw() {

    cout << "圆型" << endl;

    }

    };

    //颜色抽象类

    class Color {

    public:

    virtual void Show() = 0;

    };

    class Rad : public Color {

    public:

    void Show() {

    cout << "红色" << endl;

    }

    };

    class Blue : public Color {

    public:

    void Show() {

    cout << "蓝色" << endl;

    }

    };

    //工厂抽象类

    class AbstractFactory {

    public:

    virtual Shape *getShape(int type) = 0;

    virtual Color *getColor(int type) = 0;

    };

    class ShapeFactory : public AbstractFactory {

    public:

    Shape *getShape(int type) {

    Shape *sp = nullptr;

    switch (type) {

    case 1: sp = new Rect(); break;

    case 2: sp = new Circ(); break;

    default: cout << "unknow type!" << endl; break;

    }

    return sp;

    }

    Color *getColor(int type) {

    cout << "这是形状主场" << endl;

    return nullptr;

    }

    };

    class ColorFactory : public AbstractFactory {

    public:

    Shape *getShape(int type) {

    cout << "这是颜色主场" << endl;

    return nullptr;

    }

    Color *getColor(int type) {

    Color *cl = nullptr;

    switch (type) {

    case 1: cl = new Rad(); break;

    case 2: cl = new Blue(); break;

    default: cout << "unknow type" << endl; break;

    }

    return cl;

    }

    };

    AbstractFactory *getFactory(int type) {

    AbstractFactory *af = nullptr;

    switch (type) {

    case 1: af = new ShapeFactory(); break;

    case 2: af = new ColorFactory(); break;

    default: cout << "unknow type" << endl; break;

    }

    return af;

    }

    int main()

    {

    AbstractFactory *shapeF = getFactory(1);

    AbstractFactory *colorF = getFactory(2);

    Shape *rect = shapeF->getShape(1);

    rect->Draw();

    Shape *circ = shapeF->getShape(2);

    circ->Draw();

    Color *rad = colorF->getColor(1);

    rad->Show();

    Color *blue = colorF->getColor(2);

    blue->Show();

        std::cout << "Hello World!\n";

    }

    相关文章

      网友评论

          本文标题:抽象工厂模式

          本文链接:https://www.haomeiwen.com/subject/kvjbaftx.html