hooyantsing's Blog

P16 开闭原则

字数统计: 276阅读时长: 1 min
2020/11/07

尚硅谷Java设计模式(图解+框架源码剖析)

开闭原则

类、模块和函数应该对扩展开放,修改关闭。用抽象构建框架,用实现扩展细节。

非开闭原则
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
35
36
37
38
39
40
41
42
package xyz.hooy.principle.ocp;

public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawRectangle(new Rectangle());
graphicEditor.drawCircle(new Circle());
}
}

class GraphicEditor {
public void drawShape(Shape s){
if (s.m_type == 1){
drawRectangle(s);
} else {
drawCircle(s);
}
}

public void drawRectangle(Shape r){
System.out.println("矩形");
}
public void drawCircle(Shape r){
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;
}
}
开闭原则
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
35
36
37
38
39
40
package xyz.hooy.principle.ocp;

public class Ocp {
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){
s.draw();
}
}

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("圆形");
}
}
CATALOG
  1. 1. 开闭原则
    1. 1.1. 非开闭原则
    2. 1.2. 开闭原则