設計模式 - 開閉原則
即 對立與統一原則
什么是開閉原則
軟件實體應該對擴展開放,對修改關閉,即實體應當通過擴展實現變化,而不是修改代碼實現變化
什么是軟件實體,項目或軟件中按照一定邏輯規划划分的模塊
抽象 類
方法
書店銷售書籍

然后書寫代碼如下
// 書籍接口
public interface Ibook{
// 名稱
public String getName();
// 售價
public int getPrice();
// 作者
public String getAuthor();
}
書店出售小說類書籍,書寫代碼
public class NoveIBook implements IBook {
// 名稱
private String name;
// 價格
private int price;
// 作者
private String author;
// 構造函數
public NoveIBook(String _name, int _price, String _author){
this.name = _name;
this.price = _price;
this.author = _author;
}
// 獲得作者
public String getAuthor(){
return this.author;
}
// 價格
public String getPrice(){
return this.price;
}
// 名字
public String getName(){
return this.name;
}
}
其中,價格定義為int,不是錯誤,非金融類項目,取兩位精度,運算過程中,擴大100倍,展示時縮小100倍。
售書
public class BookStore {
private final static ArrayList bookList = new ArrayList();
// 下發的內容,是放置在持久層,即保存到硬盤中的
// java的三層架構為視圖層,服務層,持久層。
// view 層 用於接收用戶提交的請求代碼
// service 系統的業務邏輯
// dao 持久層,操作數據庫代碼
// 上下層,通過接口聯系
static{
bookList.add(new NoveIBook("", 3200, ""));
}
// 買書
public static void main(String[] args){
// 大數格式化
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setMaximumFractionDigits(2);
for(IBook book:bookList){
System.out.println(book.getName() + book.getPrice() + book.getAuthor());
}
}
}
然后,發生打折。
修改接口
接口不應該修改,因為接口是持久的
修改實現類
修改getPrice()方法達到打折的目的。
但是,因為采購書籍的人,要看到實現的價格。所以不修改
擴展實現
再增加一個子類,如下

代碼如下
// 打折銷售的小說
public class OffNovelBook extends NoveIBook {
public OffNoveIBook(String _name, int _price, String _author){
super(_name, _price, _author);
}
// 覆蓋銷售
@Override
public int getPrice(){
return super.getPrice()*90 / 100;
}
}
接着修改main里面的內容即可。
變化
變化分為邏輯變化,子模塊變化,可見視圖變化。
使用開閉原則
抽象約束
抽象約束對一組事物的描述。
當商店增加了一個計算機書籍的銷售。但是計算機書籍還有很多種,有編程語言,數據庫等。

// 增加計算機書籍接口
public interface IComputerBook extends IBook{
// 計算機書籍
public String getScope(); // 計算機書籍的范圍
}
同樣的,書寫計算機書籍類
public class ComputerBook implements IComputerBook{
private String name;
private String scope;
private String author;
public ComputerBook(String _name, int _price, String _author, String _scope){
this.name = _name;
this.price = _price;
this.author = _author;
this.scope = _scope;
}
public String getScope(){
return this.scope;
}
public String getName(){
return this.name;
}
public int getPrice(){
return this.price;
}
}
直接在main中添加即可。
總結 ; 對擴展開放,前提對抽象約束。
元數據控制模塊
即,使用配置參數,控制模塊行為。
原則總結
單一職責
類的職責要單一
里氏替換
里氏替換原則不能破壞繼承
即,子類對象,可以代替超類。
依賴倒置
面向接口。
即,每個接口只負責干一件事。
接口隔離
每個接口只干一件事
迪米特法則
通信通過類之間通信。兩者之間耦合度越少越好。
開閉原則
對擴展開放,對修改關閉
www.iming.info
