一、含义
对修改关闭,对扩展开放。
开闭原则是编程中最基础,最核心的原则。就是指类或者模块或者软件对扩展开放,对修改关闭。用抽象去搭建框架,用实现去扩展细节,当软件功能需要发生变化时,应该使用扩展的方式去应对变化,而不是修改原有的逻辑去应对变化。
二、开闭原则 反例
package principle.OCP;
public class OpenClosedPrincipleCounterexample {
public static void main(String[] args) {
MotorVehicleProduction mvp = new MotorVehicleProduction();
mvp.product(new Bus());
mvp.product(new SedanCar());
}
}
class MotorVehicleProduction {
public void product(MotorVehicle mv){
if (mv.type == 1){
productBus(mv);
}else if (mv.type == 2){
productSedanCar(mv);
}
}
public void productBus(MotorVehicle mv){
System.out.println("生产" + mv.name + "=======");
}
public void productSedanCar(MotorVehicle mv){
System.out.println("生产" + mv.name + "------");
}
}
class MotorVehicle {
protected int type;
protected String name;
}
class Bus extends MotorVehicle {
Bus(){
super.type = 1;
super.name = "大巴车";
}
}
class SedanCar extends MotorVehicle {
SedanCar(){
super.type = 2;
super.name = "小轿车";
}
}
三、开闭原则 正例
package principle.OCP;
public class OpenClosedPrinciple {
public static void main(String[] args) {
MotorVehicleProduction1 mvp = new MotorVehicleProduction1();
mvp.product(new Bus1());
mvp.product(new SedanCar1());
mvp.product(new Tractor());
}
}
class MotorVehicleProduction1 {
public void product(MotorVehicle1 mv){
mv.product();
}
}
abstract class MotorVehicle1 {
protected int type;
protected String name;
protected abstract void product();
}
class Bus1 extends MotorVehicle1 {
Bus1(){
super.type = 1;
super.name = "大巴车";
}
@Override
protected void product() {
System.out.println("生产" + this.name + "======");
}
}
class SedanCar1 extends MotorVehicle1 {
SedanCar1(){
super.type = 2;
super.name = "小轿车";
}
@Override
protected void product() {
System.out.println("生产" + this.name + "------");
}
}
class Tractor extends MotorVehicle1 {
Tractor(){
super.name = "拖拉机";
}
@Override
protected void product() {
System.out.println("生产" + this.name + "%%%%%%");
}
}
四、内容对比
