# 基本介绍

1. 开闭原则（Open Closed Principle）是编程中最基础、最重要的设计原则
2. 一个软件实体如类，模块和函数应该对扩展开放(对提供方)，对修改关闭(对使用方)。用抽象构建框架，用实现扩展细节。
3. 当软件需要变化时，尽量通过扩展软件实体的行为来实现变化，而不是通过修改已 有的代码来实现变化。
4. 编程中遵循其它原则，以及使用设计模式的目的就是遵循开闭原则

# 案例

public class test {
public static void main(String[] args) {
Paintbrush graphicEditor = new Paintbrush();
Shape rectangle = new Rectangle();
Shape circle = new Circle();
graphicEditor.drawShape(rectangle);
graphicEditor.drawShape(circle);
}
}

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

private void drawRectangle(Shape r) {
System.out.println(" 矩形 ");

}

private 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;

}

}



# 改进

public class test {
public static void main(String[] args) {
Paintbrush graphicEditor = new Paintbrush();
Shape rectangle = new Rectangle();
Shape circle = new Circle();
Shape triangle  = new Triangle();
Shape otherGraphic = new OtherGraphic();
graphicEditor.drawShape(rectangle);
graphicEditor.drawShape(circle);
graphicEditor.drawShape(triangle);
graphicEditor.drawShape(otherGraphic);
}
}

class Paintbrush {
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(" 圆形 ");
}

}

class Triangle extends Shape {
Triangle() {
super.m_type = 3;
}

@Override
public void draw() {
System.out.println(" 三角形");
}
}

class OtherGraphic extends Shape {
OtherGraphic() {
super.m_type = 4;
}

@Override
public void draw() {
System.out.println(" 其他图形");
}
}



# 总结

posted @ 2019-08-12 20:03  正号先生  阅读(390)  评论(0编辑  收藏