开闭原则(Open-Closed Principle)是指一个软件实体如类、模块和函数应该对扩展开放, 对修改关闭。所谓的开闭,也正是对扩展和修改两个行为的一个原则。强调的是用抽象构建框架,用实现扩展细节。
public interface ICourse {
Integer getId();
String getName();
Double getPrice();
}
public class Course implements ICourse{
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;
}
public Integer getId() {
return this.id;
}
public String getName() {
return this.name;
}
public Double getPrice() {
return this.price;
}
}
public class JavaDiscountCourse extends Course {
public JavaDiscountCourse(Integer id, String name, Double price) {
super(id, name, price);
}
//假设双12活动,java课程打6折优惠逻辑处理
public Double getDiscountPrice(){
return super.getPrice() * 0.6;
}
}
public class VueDiscountCourse extends Course {
public JavaDiscountCourse(Integer id, String name, Double price) {
super(id, name, price);
}
//假设双12活动,vue课程打7折优惠逻辑处理
public Double getDiscountPrice(){
return super.getPrice() * 0.7;
}
}
public class OpenCloseTest {
public static void main(String[] args) {
//创建一个java课程
ICourse iCourse = new JavaDiscountCourse(1,"Java架构",11800D);
JavaDiscountCourse discountCourse = (JavaDiscountCourse)iCourse;
System.out.println(
"课程ID:" + discountCourse.getId() +
"\n课程标题:《" + discountCourse.getName() + "》"
+"\n原价:" + discountCourse.getPrice()
+ "\n售价:" + discountCourse.getDiscountPrice()
);
//创建一个vue课程
ICourse iCourse = new VueDiscountCourse(1,"vue课程",11800D);
VueDiscountCourse discountCourse = (VueDiscountCourse)iCourse;
System.out.println(
"课程ID:" + discountCourse.getId() +
"\n课程标题:《" + discountCourse.getName() + "》"
+"\n原价:" + discountCourse.getPrice()
+ "\n售价:" + discountCourse.getDiscountPrice()
);
}
}
执行结果:
创建一个接口和实现中抽象方法和实现,保持结构不变关闭的修改,
如果我们对实现类中的功能不满足,可以创建一个类继承实现类来扩展功能满足需要,应该对扩展开放。
java 代码实现
public interface Book{
public String getName();//获取书名
public double getPrice(); //获取价格
}
public class BookeImp implements Book {
@Override
public String getName() {
return "书";
}
@Override
public double getPrice() {
return 10.0;
}
}
public class JavaBook extends BookeImp {
public String getName() {
return "Java书";
}
public double getPrice() {
return 100.0;
}
}
public class Use {
public static void main(String[] args) {
//需求打印通用书名和价格
Booke book = new BookeImp();
System.out.println(book.getName());
System.out.println(book.getPrice());
//修改需求打印java书名和价格,保持原有抽象类和现实的结构修改关闭,扩展新的需求功能
Booke javaBook = new JavaBook();
System.out.println(javaBook.getName());
System.out.println(javaBook.getPrice());
}
}