Open-Closed Principle 开闭原则

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));

    }
}

类图

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值