lxidea的 Boolan C++设计模式 第二周作业

针对DrawingSystem中的基类Shape和各个子类Line、Rec、Circle。为支持更多的形状子类,请使用某种模式来支持灵活地创建它们。使用松耦合面向对象设计方法和思想,可使用伪码表示设计。

(使用当周的设计模式,并且只使用1种设计模式)

既然本周的开头采用的是工厂方法,那么就使用工厂方法来对DrawingSystem来设计吧。针对松耦合面向对象设计方法和思想,首先设计基类

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

再为Shape设计一个工厂基类

class ShapeFactory{
        virtual shape* createShape(Point&, double)=0;
        virtual ~Shape();
}

接下来,为子类Line、Rec、Circle设计各自的类实现与各自的工厂

class Point {
public:
        double x;
        double y;
        Point(double _x=0, double _y=0):x(_x),y(_y){};
}

class Line: public Shape {
protected:
        Point p1,p2;
public:
        Line():Shape(){};
        virtual void draw(){
            //draw line.....
        }
        SetStPoint(const Point& p);
        SetEndPoint(const Point& p);
        ~Line();
}

class LineFactory: public ShapeFactory{
        virtual shape* createShape(){
              Line* l = new Line();
              l->setStPoint(...);
              l->setEndPoint(...);
              return l;
        }
}

class Rec: public Shape {
protected:
        Point p;
        double length;
        double height;
public:
        Line():Shape(){};
        virtual void draw(){
            //draw rectangle.....
        }
        setStPoint(Point& p);
        setHeight(double h);
        setWidth(double w);
        ~Rec();
}

class RecFactory: public ShapeFactory{
        virtual shape* createShape(){
              Rec* r = new Rec();
              r->setStPoint(...);
              r->setHeight(...);
              r->setWidth(...);
              return r;
        }
}

class Circle: public Shape {
protected:
        Point p;
        double radius;
public:
        Circle():Shape(){};
        virtual void draw(){
            //draw Circle.....
        }
        setCenter(Point& p);
        setRadius(double r);
        ~Circle();
}

class CircleFactory: public ShapeFactory{
        virtual shape* createShape(){
              Circle* c = new Circle();
              c->setCenter(...);
              c->setRadius(...);
              return c;
        }
}

如此这样,DrawingSystem中在使用的时候,只需要传入对应的对象工厂就可以向DrawingSystem中添加各种形状了。

class DrawingSystem {
protected:
        std::list myshapes;
public:
        DrawingSystem();
        void addShape(ShapeFactory* _shapefactory) {
              Shape* s = _shapefactory::createShape();
              myshapes.add(s);
        }
        void removeShape(Shape* _s) {
              myshapes.remove(s);
              delete s;
        }
        void draw() {
              for (auto s: myshapes)
                  s->draw();
        }
        ~DrawingSystem() {
                for (auto s: myshapes)
                      delete s;
        }
}

你可能感兴趣的:(lxidea的 Boolan C++设计模式 第二周作业)