工厂模式

1 方式一。改动基类的方式实现,这种方式再新类型加入时需要重新修改基类,不是最便捷的方式。

//fatory
#include <iostream>
#include <stdexcept>
#include <cstddef>
#include <string>
#include <vector>

using namespace std;

class Shape
{
public:
    virtual void draw() = 0;
    virtual void erase() = 0;
    virtual ~Shape() {}
    class BadShapeCreation : public logic_error
    {
    public:
        BadShapeCreation(string type) : logic_error ("Cannot create type" + type) {}
    };
    static Shape *factory(const string &type) throw(BadShapeCreation);
};

class Circle : public Shape
{
private:
    Circle() {}
    friend class Shape;
public:
    void draw() {cout << "Circle::draw" << endl;}
    void erase() {cout << "Circle::erase" << endl;}
    ~Circle() {cout << "Circle::~Circle" << endl;}
};

class Square : public Shape
{
private:
    Square() {}
    friend class Shape;
public:
    void draw() {cout << "Square::draw" << endl;}
    void erase() {cout << "Square::erase" << endl;}
    ~Square() {cout << "Square::~Square" << endl;}
};

Shape * Shape::factory( const string &type ) throw(BadShapeCreation)
{
    if (type == "Circle") return new Circle;
    if (type == "Square") return new Square;
    throw BadShapeCreation(type);
}

char *sl[] = 
{
    "Circle", "Square", "Square", "Square",
    "Circle", "Circle", "Circle","Square"
};

int main()
{    
    Shape * p1 = Shape::factory(sl[0]);
    Shape * p2 = Shape::factory(sl[1]);

    p1->draw();
    p2->draw();

    return 0;
}

 

posted @ 2013-09-26 17:17  calabashdad  阅读(150)  评论(0编辑  收藏  举报