开闭原则

开闭原则

Open Closed Principle

基本介绍

  • 开闭原则是编程中最基础、最重要的设计原则
  • 一个软件实体如类,模块和函数应该对扩展开放,对修改关闭。用抽象构建框架,用实体扩展细节。
  • 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
  • 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Ocp{
public status void main(String[] args){
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
}
}
class GraphicEditor{
public void drawShape(Shape shape){
shape.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("绘制圆形")
}
}