經過面向接口編程能夠下降程序的耦合。java
1. 簡單工廠模式編程
將全部生成對象的邏輯集中在工廠類管理,而全部須要使用該對象的類只需與該接口耦合,而不是與具體的實現類耦合。若是系統須要重構,須要替換對象,能夠直接對工廠類(接口)進行更改。數組
2. 命令模式code
某個方法須要完成某一個行爲,但這個行爲的具體實現沒法肯定,必須等到執行該方法時才能夠肯定。例:假設有革個方法須要遍歷某個數組的數組元素,但沒法肯定在遍歷數組元素時 如何 處理這些元素,須要在調用該方法時指定具體的處理行爲。對象
這就須要把「處理行爲」做爲參數傳入方法。接口
由於Java不容許代碼塊單獨存在,因此我麼使用Command接口來定義一個方法,使用這個方法來封裝「處理對象」。get
public interface Command { //接口裏定義的process方法用於封裝」處理行爲「 void process(int[] target); }
下面是須要處理數組的處理類,在這個處理類中包含一個process方法,這個方法沒法肯定處理數組的處理行爲,因此定義該方法時使用了一個Command參數,這個Command參數負責對數組的處理行爲。cmd
public class ProcessArray { public void process(int[] target, Command cmd) { cmd.process(target); } }
經過一個Command接口,就實現了讓ProcseeArray類和集體"處理行爲"的分離,程序使用此接口表明了對數組的處理行爲。Command接口也沒有提供真正的處理,只有等到須要調用ProcessArray對象的process方法時,才真正傳入一個Command對象,才肯定對數組的處理行爲。class
public class CommandTest { public static void main (String [] args) { ProcessArray pa = new ProcessArray(); int[] target = {3,-4,6,4}; //第一次處理數組,具體處理行爲取決與PrintCommand pa.process(target,new PrintCommand()); System.out.println("----------"); //第二次處理數據,具體處理行爲取決於AddCommand pa.process(target , new AddCommand()); } }
上面程序顯示了兩次不一樣處理行爲的效果,也就實現了process方法和」處理行爲「的分離,兩次不一樣的處理行爲是經過PrintCommand類和AddCommand類提供的。重構
public class PrintCommand implements Commmand { public void process (int[]target) { for (int tmp: target) { System.out.println("迭代輸出目標數組的元素:"+ tmp); } } }
public class AddCommand implements Commmand { public void process (int[]target) { int sum = 0; for (int tmp: target) { sum += tmp; System.out.println("數組元素的總和是:"+ sum); } } }