Open-Closed Principle 开闭原则
简介
定义:一个软件实体如类、模块和函数应该对扩展开放,对修改关闭
主要和核心思想
强调用抽象构建框架,用实现扩展细节
优点
- 提高软件系统的可复用性及可维护性
实践案例
手机为例:手机售价618促销
public interface IPhone {
Integer getId();
String getModel();
String getSpecification();
Double getPrice();
}
public class XiaoMiPhone implements IPhone {
private Integer id;
private String model;
private String specification;
private Double price;
public XiaoMiPhone(Integer id, String model, String specification, Double price) {
this.id = id;
this.model = model;
this.specification = specification;
this.price = price;
}
@Override
public Integer getId() {
return this.id;
}
@Override
public String getModel() {
return this.model;
}
@Override
public String getSpecification() {
return this.specification;
}
@Override
public Double getPrice() {
return this.price;
}
}
public class RedMiK30ProDiscountPhone extends XiaoMiPhone {
public RedMiK30ProDiscountPhone(Integer id, String model, String specification, Double price) {
super(id, model, specification, price);
}
public Double getDiscountPrice(Double discountPrice){
return super.getPrice()-discountPrice;
}
}
public class PhoneTest {
public static void main(String[] args) {
IPhone phone = new RedMiK30ProDiscountPhone(1, "RedMi K30 Pro", "6+128", 2999.0);
RedMiK30ProDiscountPhone discountPhone = (RedMiK30ProDiscountPhone) phone;
System.out.println("手机ID === "+discountPhone.getId()
+"\n手机型号 === " +discountPhone.getModel()
+"\n手机规格 === " +discountPhone.getSpecification()
+ "\n手机原价 === " + discountPhone.getPrice()
+ "\n手机活动价 ===" +discountPhone.getDiscountPrice(600.0));
}
}