对扩展开放,对修改关闭。强调的是用抽象构建框架,有实现扩展细节。
举个栗子:
以商品为例,首先创建一个商品接口:
import java.math.BigDecimal;
public interface Commodity {
// 商品ID
int getId();
// 商品名称
String getName();
// 商品价格
BigDecimal getPrice();
}
商品有很多,创建一个手机商品:
import java.math.BigDecimal;
public class PhoneCommodity implements Commodity {
private int id;
private String name;
private BigDecimal price;
public PhoneCommodity(int id, String name, BigDecimal price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public int getId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
@Override
public BigDecimal getPrice() {
return this.price;
}
}
如果这个时候要给手机降价,直接修改PhoneCommodity中的getPrice()则会存在一定的风险,可能影响其他地方的调用结果。那么我们如何在不修改原有代码的前提下,实现价格优惠这个功能呢?现在我们再写一个价格优惠的类。
import java.math.BigDecimal;
public class PhoneDiscountCommodity extends PhoneCommodity{
public PhoneDiscountCommodity(int id, String name, BigDecimal price) {
super(id, name, price);
}
public BigDecimal getOriginalPrice() {
return super.getPrice();
}
public BigDecimal getPrice() {
return getOriginalPrice()
// 六折
.multiply(new BigDecimal("0.6"))
// 保留两位小数点,多于的直接去掉
.setScale(2, BigDecimal.ROUND_DOWN);
}
}