Introduce the principle of open and closed:
1) closing principle (Open Closed Principle) programming the most basic and important design principles
2) a software entity, such as classes, modules and functions should be open for extension (for provider), closed for modification (to the consumer) . Abstract framework for building, implemented with extension detail.
3) When the software needs to change, try to achieve changes in behavior by extending the software entity, rather than to achieve change by modifying existing code.
4) follow other programming principles and design patterns object is to follow the principle of opening and closing.
Examples of errors
Package com.kittenplus.principle.ocp; public class OCP { public static void main (String [] args) { GraphicEditor GE = new new GraphicEditor (); ge.drawShape ( new new the Rectangle ()); ge.drawCircle ( new new Circle () ); }} // this is a drawing for class class GraphicEditor { // receiving Shape object, and then draw a different pattern according to the type public void the drawShape (Shape S) { IF (s.m_type ==. 1 ) drawRectangle (S ); the else IF (s.m_type == 2) drawCircle(s); } public void drawRectangle(Shape r) { System.out.println("绘制矩形");} public void drawCircle(Shape r) { System.out.println("绘制圆形"); }} //Shape 类 基类 class Shape { int m_type; } class Rectangle extends Shape { Rectangle() { super.m_type = 1; }} class Circle extends Shape { Circle() { super.m_type = 2; } }
Package com.kittenplus.principle.ocp; public class OCP { public static void main (String [] args) { GraphicEditor GE = new new GraphicEditor (); ge.drawShape ( new new the Rectangle ()); ge.drawShape ( new new Circle () ); ge.drawShape ( new new Triangle ()); ge.drawShape ( new new OtherGraphic ()); }} // this is a drawing for class class GraphicEditor { // receiving Shape object, and then draw a different pattern according to type public void drawShape(Shape s) { s.draw(); } } //Shape 类 基类 abstract class Shape { int m_type; public abstract void draw();//抽象方法 } class Rectangle extends Shape { Rectangle() { super.m_type = 1; } @Override public void draw() { System.out.println(" 绘制矩形"); } } class Circle extends Shape { Circle() { super.m_type = 2; } @Override public void draw() { System.out.println(" 绘制圆形"); } } class Triangle extends Shape{ Triangle(){ super.m_type=3; } @Override public void draw() { System.out.println(" 绘制三角形"); } } class OtherGraphic extends{The Shape OtherGraphic () { Super .m_type. 4 = ; } @Override public void Draw () { System.out.println ( "drawing other graphic" ); } }