设计模式-开闭原则

1. 概述

在这里插入图片描述

2. 代码示例分析

  1. 在测试类上有详细的解析
/**
 * 书写固定的基础结构, 不应该轻易改变;
 * 是所有实现类的抽象交集.
 */
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;
    }
    
    /**
     * 获取折后价格.
     * @return: 折后价格
     */
    public BigDecimal getDiscountPrice() {        
    	return this.getPrice().multiply(getDiscount());
    }
}



/**
 * 开闭原则coding解析:
 * 1. ICourse: 定义固定的基础架构
 * 2. JavaCourse: 实现ICourse的接口.
 * 3. 当出现需要打折的价格时, 若是修改ICourse就会导致, 大量的实现类,
 * 需要添加新的代码去实现接口, 而且你无法保证所有的实现类都需要实现这个接口.
 * 4. 虽然java8提供了default方法, 自己实现方法, 这样会导致所有的实现类都能调用此方法, 但可能并不是所有实现类都需要.
 * 5. JavaDiscountCourse继承了JavaCourse, 可以定义专门的实现. 不会污染接口, 也不会污染其它的实现类.
 */
public class OpenClosePatternTest {
    public static void main(String[] args) {
        ICourse iCourse = new JavaDiscountCourse(1L, "JAVA", new BigDecimal("642"));

        // 面向interface, 无法获取到实现类中自己的方法; 因此需要强制类型转换.
        JavaDiscountCourse discountCourse = (JavaDiscountCourse) iCourse;

        // 设置折扣
        discountCourse.setDiscount(new BigDecimal("0.8"));

        // print: Id: 1, name: JAVA, price: 642, discountPrice: 513.6
        System.out.println("Id: " + discountCourse.getId() + ", name: " + discountCourse.getName()                + ", price: " + discountCourse.getPrice() + ", discountPrice: " + discountCourse.getDiscountPrice());
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值