Interface Segregation Principles(ISP)java
接口应该细化, 不要使用过于臃肿的接口. 客户端须要什么接口就提供什么接口, 将不须要的接口剔除掉.
不要将太多的方法放在同一个接口之中.markdown
可是接口设计也要有度, 不可过分设计, 这个度每每根据经验和常识判断.ide
Law of Demeter(LOD) , 最少知识原则(Least Knowledge Principle))函数
一个对象应该对其它对象有最少的了解, 另外一个解释是只与直接的朋友通讯.this
朋友类: 出如今成员变量, 方法的输入输出参数中的类称为成员朋友类, 而出如今方法体内部的类不属于朋友类
Open Close Principle(OCP)spa
一个软件实体如类, 模块和函数等应该对扩展开放, 对修改关闭.设计
interface IBook{
public String getName();
public int getPrice();
public String getAuthor();
}
class NovelBook implements IBook{
private String name;
private int price;
private String author;
public NovelBook(String name, int price, String author){
this.name=name;
this.price=price;
this.author=author;
}
@Override
public String getName() {
return name;
}
@Override
public int getPrice() {
return price;
}
@Override
public String getAuthor() {
return author;
}
}
若是未来要搞打折, 通常可能会用如下两个方法来解决:code
getOffPrice()
方法. 可是这须要对每个实现IBook
接口的实现类都添加该方法, 工做繁琐. 且接口应该是稳定且可靠的, 不该该常常发生变化.getPrice()
中实现打折处理, 可是若是仍须要知道原价是多少, 就会出问题.添加一个子类对象
class OffNovelBook extends NovelBook{
public OffNovelBook(String name,int price, String author){
super(name,price,author);
}
@Override
public int getPrice(){
int selfPrice=super.getPrice();
int offPrice=selfPrice*90/100;
return offPrice;
}
}