翻译自http://www.oodesign.com

设计原则之开闭原则


动机:一个聪明的应用设计和代码编写应该考虑到开发过程中的频繁修改代码。通常情况下,一个新功能的增加会带来很多的修改。这些修改已存在的代码应该要最小化,

总结:软件应该对扩展开发,对修改关闭。装饰器模式,观察者模式,工厂模式可以帮助我们队代码做最小的修改。

Bad Example:

    缺点:

        1、当新的shape被添加,开发者要花大量时间去理解GraphicEditor源码。。

        2、添加新shape也许会影响已经存在的功能

spacer.gif

// Open-Close Principle - Bad example

 class GraphicEditor {

     public void drawShape(Shape s) {

         if (s.m_type==1)

             drawRectangle(s);

         else if (s.m_type==2)

             drawCircle(s);

     }

     public void drawCircle(Circle r) {....}

     public void drawRectangle(Rectangle r) {....}

 }

 class Shape {

     int m_type;

 }

 class Rectangle extends Shape {

     Rectangle() {

         super.m_type=1;

     }

 }

 class Circle extends Shape {

     Circle() {

         super.m_type=2;

     }

 } 

Good Example

    优点:

        1、不需要理解GraphicEditor源码。

        2、画图功能代码移到每个具体的shape类,降低了修改老功能代码。

spacer.gif

// Open-Close Principle - Good example
 class GraphicEditor {
 	public void drawShape(Shape s) {
 		s.draw();
 	}
 }

 class Shape {
 	abstract void draw();
 }

 class Rectangle extends Shape  {
 	public void draw() {
 		// draw the rectangle
 	}
 }