开闭原则(非常重要的原则)
定义
-
一个软件实体如类,模块和函数应该对扩展开放,对修改关闭
-
用抽象构建框架,用实现扩展细节
优点
- 提高软件系统的可复用性,可维护性
核心思想
- 面向抽象编程,当有新的功能时应该不需要修改之前的代码,而是新增
代码示例
/**
* 开闭原则
*/
public class OpenClose {
public static void main(String[] args) {
Course course = new JavaDiscountCourse(1, "java开发", 200);
JavaDiscountCourse javaDiscountCourse = (JavaDiscountCourse) course;
System.out.println(String.format("课程ID:%s,课程名称:%s,课程原价:%s,课程打折价:%s",
course.getId(), course.getName(), javaDiscountCourse.getOriginPrice(), course.getPrice()));
}
}
/**
* 课程
*/
interface Course {
Integer getId();
String getName();
Double getPrice();
}
/**
* java课程
*/
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;
}
}
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;
}
}