每一个模式描述了一个在我们周围不断重复发生的问题,以及该问题解决方案的核心。这样,你就能一次又一次地使用该方案而不必做重复劳动。——Christopher Alexander
避免重复发明轮子。 |
使用面向对象的手法实现可复用的目标。 |
从面向对象谈起
底层思维:死扣语言细节,比如《深度探索C++对象模型》,力求从机器层面搞懂从编译到运行的所有细节。 抽象思维:架构设计,将具体问题转化成代码设计。 底层思维决定了对编程语言的熟练程度,抽象思维决定了能否使用编程语言高效解决具体问题。 |
建筑商从来不会想给一栋已建好的100层高的楼房底下再新修一个小地下室——这样做花费极大而且注定要失败。然而令人惊奇的是,软件系统的用户在要求作出类似改变时却不会仔细考虑,而且他们认为这只是需要简单编程的事。——Object-Oriented Analysis and Design with Applications, Grady Booch
变化。
class Point{ public: int x; int y; }; class Line{ public: Point start; Point end; Line(const Point& start, const Point& end){ this->start = start; this->end = end; } }; class Rect{ public: Point leftUp; int width; int height; Rect(const Point& leftUp, int width, int height){ this->leftUp = leftUp; this->width = width; this->height = height; } }; //增加 class Circle{ }; |
class MainForm : public Form { private: Point p1; Point p2; vector<Line> lineVector; vector<Rect> rectVector; //改变 vector<Circle> circleVector; public: MainForm(){ //... } protected: virtual void OnMouseDown(const MouseEventArgs& e); virtual void OnMouseUp(const MouseEventArgs& e); virtual void OnPaint(const PaintEventArgs& e); }; void MainForm::OnMouseDown(const MouseEventArgs& e){ p1.x = e.X; p1.y = e.Y; //... Form::OnMouseDown(e); } void MainForm::OnMouseUp(const MouseEventArgs& e){ p2.x = e.X; p2.y = e.Y; if (rdoLine.Checked){ Line line(p1, p2); lineVector.push_back(line); } else if (rdoRect.Checked){ int width = abs(p2.x - p1.x); int height = abs(p2.y - p1.y); Rect rect(p1, width, height); rectVector.push_back(rect); } //改变 else if (...){ //... circleVector.push_back(circle); } //... this->Refresh(); Form::OnMouseUp(e); } void MainForm::OnPaint(const PaintEventArgs& e){ //针对直线 for (int i = 0; i < lineVector.size(); i++){ e.Graphics.DrawLine(Pens.Red, lineVector[i].start.x, lineVector[i].start.y, lineVector[i].end.x, lineVector[i].end.y); } //针对矩形 for (int i = 0; i < rectVector.size(); i++){ e.Graphics.DrawRectangle(Pens.Red, rectVector[i].leftUp, rectVector[i].width, rectVector[i].height); } //改变 //针对圆形 for (int i = 0; i < circleVector.size(); i++){ e.Graphics.DrawCircle(Pens.Red, circleVector[i]); } //... Form::OnPaint(e); } |
什么是好的软件设计?软件设计的金科玉律:复用!