开闭原则
基本介绍
1.开闭原则 Open Closed Principle是编程中最基础、最重要的设计原则
2.一个软件实体如类、模块、函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节
3.当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化
4.编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则
实际场景(传统方式)
实现画图形的功能
传统方式去实现:
分析:
1.优点:比较好理解,容易想到该实现方法
2.缺点:违背了设计模式的开闭原则,即对扩展开放,对修改关闭。当我们给类增加功能的时候,尽量不修改代码,或者尽可能少的去修改代码
3.例如当我们需要新增一个图形种类的时候,我们需要修改的代码就比较多
package com. tan. principle. open_closed ;
public class OpenClosed {
public static void main ( String [ ] args) {
GraphicEditor graphicEditor = new GraphicEditor ( ) ;
graphicEditor. drawShape ( new Rectangle ( ) ) ;
graphicEditor. drawShape ( new Circle ( ) ) ;
}
}
class GraphicEditor {
public void drawShape ( Shape s) {
if ( s. m_type == 1 ) {
drawRectangle ( s) ;
} else if ( s. m_type == 2 ) {
drawCircle ( s) ;
}
}
public void drawRectangle ( Shape s) {
System . out. println ( "画一个矩形" ) ;
}
public void drawCircle ( Shape s) {
System . out. println ( "画一个圆形" ) ;
}
}
class Shape {
int m_type;
}
class Rectangle extends Shape {
Rectangle ( ) {
super . m_type = 1 ;
}
}
class Circle extends Shape {
Circle ( ) {
super . m_type = 2 ;
}
}
代码改进(开闭原则)
改进的思路分析
思路:把创建Shape类做成抽象类,并提供一个抽象的draw方法,让子类去实现即可,这样我们有新的图形种类时,只需要让新的图形类继承Shape,并实现draw方法即可,使用方的代码就不需要修
-->满足了开闭原则
package com. tan. principle. open_closed. improve ;
public class OpenClosed {
public static void main ( String [ ] args) {
GraphicEditor graphicEditor = new GraphicEditor ( ) ;
graphicEditor. drawShape ( new Rectangle ( ) ) ;
graphicEditor. drawShape ( new Circle ( ) ) ;
graphicEditor. drawShape ( new Triangle ( ) ) ;
graphicEditor. drawShape ( new OtherGraphic ( ) ) ;
}
}
class GraphicEditor {
public void drawShape ( Shape s) {
s. draw ( ) ;
}
public void drawRectangle ( Shape s) {
System . out. println ( "画一个矩形" ) ;
}
public void drawCircle ( Shape s) {
System . out. println ( "画一个圆形" ) ;
}
}
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 Shape {
public OtherGraphic ( ) {
super . m_type = 4 ;
}
@Override
public void draw ( ) {
System . out. println ( " 绘制其他图形 " ) ;
}
}