一、开闭原则简介
-
定义:一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。
-
表现:用抽象构建框架,用实现扩展细节。
-
优点:提高软件系统的可复用性及可维护性。
二、代码实现
public interface Course {
Integer getId();
String getName();
Double getPrice();
}
public class JavaCourse implements Course {
private Integer id;
private String name;
private Double price;
public JavaCourse(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public Integer getId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
@Override
public Double getPrice() {
return this.price;
}
}
public class JavaDiscountCourse extends JavaCourse {
public JavaDiscountCourse(Integer id, String name, Double price) {
super(id, name, price);
}
public Double getOriginPrice() {
return super.getPrice();
}
@Override
public Double getPrice() {
return super.getPrice() * 0.8;
}
}
public class OpenCloseTest {
public static void main(String[] args) {
Course javaCourse = new JavaDiscountCourse(96, "学习设计模式", 348D);
JavaDiscountCourse javaDiscountCourse = (JavaDiscountCourse) javaCourse;
String text = String.format("课程Id:%d,课程名称:%s,课程原价:%.1f元,折后价格:%.1f元",
javaCourse.getId(), javaCourse.getName(),
javaDiscountCourse.getOriginPrice(),
javaCourse.getPrice());
System.out.println(text);
}
}
三、关于开闭原则的理解
/**
* 关于"开闭原则 "的理解:
* 我们不去修改接口,和接口已经实现的方法,因为这样会对原有代码产生影响。
* 思想:我们通过 "对接口进行不同的实现",以及"对已经实现接口的继承",来完成对新增业务的处理。
* 从而适应不同业务实现的变化。
* 通过这样的操作,变化底层的子模块,减少对其他模块的影响。即可实现对接口扩展是开放的,对接口修改是关闭的。
*/