设计模式 C++ 工厂模式

#include <iostream>

using namespace std;

class Shape
{
public:
    virtual void draw()=0;
};

class Rectangle:public Shape
{
public:
    void draw()
    {
        cout << "from rectangle"<<endl;
    }
};


class Square:public Shape
{
public:
    void draw()
    {
        cout << "from square"<<endl;
    }
};

class ShapeFatory
{
public:
    Shape* getShape(int a){
        if(a==0){
            return NULL;
        }
        else if(a==1){
            return new Rectangle();
        }
        else if(a==2){
            return new Square();
        }
        else{
            return NULL;
        }

    }
};

int main(int argc, char *argv[])
{
    ShapeFatory* fac = new ShapeFatory();

    Shape*   a1 = fac->getShape(1);
    Shape*   a2 = fac->getShape(2);

    return 0;
}

 

posted @ 2019-06-28 16:59  方豆  阅读(180)  评论(0编辑  收藏  举报