1. 概述
2. 代码示例分析
- 在测试类上有详细的解析。
public interface ICourse {
Long getId();
String getName();
BigDecimal getPrice();
}
public class JavaCourse implements ICourse {
private Long id;
private String name;
private BigDecimal price;
public JavaCourse(Long id, String name, BigDecimal price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public Long getId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
@Override
public BigDecimal getPrice() {
return this.price;
}
}
public class JavaDiscountCourse extends JavaCourse {
private BigDecimal discount;
public JavaDiscountCourse(Long id, String name, BigDecimal price) {
super(id, name, price);
}
public BigDecimal getDiscount() {
return discount;
}
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
public BigDecimal getDiscountPrice() {
return this.getPrice().multiply(getDiscount());
}
}
public class OpenClosePatternTest {
public static void main(String[] args) {
ICourse iCourse = new JavaDiscountCourse(1L, "JAVA", new BigDecimal("642"));
JavaDiscountCourse discountCourse = (JavaDiscountCourse) iCourse;
discountCourse.setDiscount(new BigDecimal("0.8"));
System.out.println("Id: " + discountCourse.getId() + ", name: " + discountCourse.getName() + ", price: " + discountCourse.getPrice() + ", discountPrice: " + discountCourse.getDiscountPrice());
}
}