矩不正,不可为方;规不正,不可为圆.——淮南子
任何行业或者圈子都有自己的规则,遵从规则是在这个行业立足的根本,不然你就会被这个行业淘汰。软件设计同样有自己的原则。遵循这样的原则,你的代码软件才能更容易被接受,才会使你更专业。
1. 开闭原则
定义
一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。
用抽象构建框架,用实现扩展细节。
优点
提高软件的可复用性及可维护性
代码
/**
* The interface Boo k.
*/
public interface Book {
/**
* Gets id.
*
* @return the id
*/
Integer getId();
/**
* Gets name.
*
* @return the name
*/
String getName();
/**
* Gets price.
*
* @return the price
*/
Double getPrice();
}
/**
* The type Java book.
*/
public class JavaBook implements Book {
private Integer id;
private String name;
private Double price;
/**
* Instantiates a new Java book.
*
* @param id the id
* @param name the name
* @param price the price
*/
public JavaBook(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
/**
* Sets id.
*
* @param id the id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Sets name.
*
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets price.
*
* @param price the price
*/
public void setPrice(Double price) {
this.price = price;
}
@Override
public Integer getId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
@Override
public Double getPrice() {
return this.price;
}
/**
* The type Discount java book.
*/
public class DiscountJavaBook extends JavaBook {
/**
* Instantiates a new Java book.
*
* @param id the id
* @param name the name
* @param price the price
*/
public DiscountJavaBook(Integer id, String name, Double price) {
super(id, name, price);
}
@Override
public Double getPrice() {
return super.getPrice() * 0.5;
}
}
public class Test {
public static void main(String[] args) {
Book book = new JavaBook(1, "《Java开发指南》", 79.9);
System.out.println("书本Id: " + book.getId() +
"\n书本名字: " + book.getName() +
"\n书本售价: " + book.