xule

Make progress everything
On the long way to full-stack developer, architecture

Blog Categories GitHub About

28 Oct 2014
OpenClosePriciple(OCP)

Bad design:fixed design, when you add Triangle, it will cause Shape, Square, Circle and DrawAllShapes to rebuild and redeploy,so this design is not strong.

Bad design:

--------------------shape.h-----------
enum ShapeType { circle, square};
struct Shape {
	ShapeType itsType;
};

--------------------Circle.h----------
struct Circle {
	Shapetype itsType;
	double itsRadius;
	Point itsCenter;
};

-------------------Square.h------------
struct Square {
	ShapeType itsType;
	double itsSide;
	Point itsTopLeft;
}

---drawAllShapes.cc--------------------
typedef struct Shape *ShapePointer;

void DrawAllShapes(ShapePointer list[], int n) {
	int i;
	for (i=0; i < n; i++) {
		struct Shape* s = list[i];
		switch (s->itsType) {
			case square:
				DrawSquare((struct Square*)s);
			break;
			case circle:
				DrawCircle((struct Circle*)s);
			break;
		}
	}
}

Code obey OCP:

	class Shape {
		public:
			virtual void Draw() const = 0;
	};
	
	class Square: public Shape {
		public 
			virtual void Draw() const;
	};
	
	class Circle: public Shape {
		public:
			virtual void Draw() const;
	};
	
	void DrawAllShapes (vector<Shape*>& list) {
		vector<Shape*>::iterator I;
		for (i=list.begin(); i != list.end(); i++)
			(*i)->Draw();
	}

If customer needs to draw square before circle, we need to redesign the project and make order supported.

乐此不疲~

2014-10-24 13:41:11


xule

scribble

Blog Categories GitHub About