每天三分钟学习设计原则-开闭原则
第一篇:开闭原则
前言
为什么要学习设计原则?
设计原则其实就是一系列的设计规范,为学习设计模式奠定了基础,使我们可以写出更加优雅的程序,让程序的健壮性和可复用性及可扩展性更强.
一、开闭原则
定义:一个软件如实体类,函数和模块应该对修改关闭,对扩展开放
优点:提高程序的可扩展性和复用性
二、开闭原则代码实现
以手机为例:手机有价格和品牌属性,但是在实际生活中手机的售价可能会发生改变.
代码如下(示例):
public class MobilePhone {
//手机的品牌
private String name;
//手机的价格
private Double price;
public MobilePhone(String name, Double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
public class Test {
public static void main(String[] args) {
MobilePhone mobilePhone=new MobilePhone("huawei",5300D);
//打折
Double discount=mobilePhone.getPrice()*0.6;
System.out.println("手机的品牌:"+mobilePhone.getName()+"\r\n"+
"手机的原价:"+mobilePhone.getPrice()+"\r\n"+
"手机的售价:"+discount);
}
}
如果商场下次打折的折扣是5折,我们就需要改我们的业务代码,违反了开闭原则,使程序存在一定的风险性
//打折 Double discount=mobilePhone.getPrice()*0.5;
但是我们可以我们的程序做一个改进
增加一个打折的接口
public interface IMobilephone {
//手机打折
Double discount ();
}
实现打折接口
public class MobilePhone implements IMobilephone {
//手机的品牌
private String name;
//手机的价格
private Double price;
@Override
public Double discount() {
price=this.price*0.6;
return price;
}
public MobilePhone(String name, Double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
改进我们的业务代码:
public class Test {
public static void main(String[] args) {
MobilePhone mobilePhone=new MobilePhone("huawei",5300D);
System.out.println("手机的品牌:"+mobilePhone.getName()+"\r\n"+
"手机的原价:"+mobilePhone.getPrice()+"\r\n"+
"手机的售价:"+mobilePhone.discount()
);
}
}
这样我们下次如果在打折的时候,就不用修改我们的业务代码,只需要修改实现打折接口的方法即可。
@Override public
Double discount() {
price=this.price*0.5;
return price; }
总结
以上就是今天对开闭原则的讲解,本文对开闭原则定义和优点的介绍,通过生活中商场手机打折的一个事例对开闭原则进行了更加详细的说明,通过简单的3分钟即可掌握。