1 基本介绍
开闭原则(OCP:Open Closed Principle):一个软件实体如类,模块和函数应该对扩展开放,对修改关闭。用抽象构建架构,用实现扩展细节。当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
2 案例演示
public class Exer {
public static void main(String[] args) {
Coach coach = new Coach();
coach.execPlay(new Runner());
coach.execPlay(new Jumper());
}
}
class Coach {
public void execPlay(Sportsman man) {
if (man.playType == 1) {
execRun(man);
} else if (man.playType == 2) {
execJump(man);
}
}
public void execRun(Sportsman man) {System.out.println("去跑步");}
public void execJump(Sportsman man) {System.out.println("去跳");}
}
class Sportsman {
int playType;
}
class Runner extends Sportsman {
int playType = 1;
}
class Jumper extends Sportsman {
int playType = 2;
}
分析:
① 优点:简单易操作
② 违反开闭原则,即对扩展开放,对修改关闭。即当我们给类增加新功能时,尽量不要修改代码,或者尽可能少修改代码。
当我新增功能时上面的代码就会需要改动很多地方,优化:
public class Exer {
public static void main(String[] args) {
Coach coach = new Coach();
coach.execPlay(new Runner());
coach.execPlay(new Jumper());
coach.execPlay(new Swimer());
}
}
class Coach {
public void execPlay(Sportsman man) {
man.execPlay();
}
// public void execRun(Sportsman man) {System.out.println("去跑步");}
// public void execJump(Sportsman man) {System.out.println("去跳");}
}
abstract class Sportsman {
int playType;
public abstract void execPlay();
}
class Runner extends Sportsman {
public Runner {super.playType = 1;}
@Override
public void execPlay() {System.out.println("去跑步");}
}
class Jumper extends Sportsman {
public Jumper {super.playType = 2;}
@Override
public void execPlay() {System.out.println("去跳");}
}
// 新增功能
class Swimer extends Sportsman {
public Swimer {super.playType = 3;}
@Override
public void execPlay() {System.out.println("去游泳");}
}