1. 开闭原则
开闭原则(Open Close Principle):
- 开闭原则是编程中最基础、最重要的设计原则
- 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节。
- 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
- 面向接口编程
1.1 案例
- 代码
public class OpenClosePrinceOne {
public static void main(String[] args) {
GraphicEditor graphicEditor =new GraphicEditor();
graphicEditor.drawGraphice(new Rectangle());
graphicEditor.drawGraphice(new Circle());
}
}
//画图工具类 【使用方】
class GraphicEditor{
public void drawGraphice(Shap shap){
if(shap.type==1){
drawRectangle();
}
if(shap.type==2){
drawCircle();
}
}
public void drawCircle() {
System.out.println("画圆形");
}
public void drawRectangle() {
System.out.println("画矩形");
}
}
//基类
abstract class Shap{
int type;
}
//矩形
class Rectangle extends Shap{
Rectangle(){
type=1;
}
}
//圆形
class Circle extends Shap{
Circle(){
type=2;
}
}
- 思考
问题:如果现在要新增一个三角形呢,我们是不是要改动使用方(GraphicEditor),但是有没有办法不改变使用方呢?
方案:开闭原则 - 改进
public class OpenClosePrinceOne {
public static void main(String[] args) {
GraphicEditor graphicEditor =new GraphicEditor();
graphicEditor.drawGraphice(new Rectangle());
graphicEditor.drawGraphice(new Circle());
}
}
//画图工具类 【使用方】
class GraphicEditor{
public void drawGraphice(Shap shap) {
shap.draw();
}
}
abstract class Shap{
int type;
abstract void draw();
}
//矩形
class Rectangle extends Shap{
Rectangle(){
type=1;
}
@Override
void draw() {
System.out.println("画矩形");
}
}
class Circle extends Shap{
Circle(){
type=2;
}
@Override
void draw() {
System.out.println("画圆形");
}
}
1.2 总结
- 使用方通过使用抽象来避免修改(接口、抽象类),提供方通过实现抽象来扩展功能。
- 开闭原则是最基本,也是最重要的一个原则