Java開發中的23種設計模式詳解之二:7種結構型模式

Mr_Alexander發表於2016-05-23

我們接著討論設計模式,上篇文章我講完了5種建立型模式,這章開始,我將講下7種結構型模式:介面卡模式、裝飾模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。其中物件的介面卡模式是各種模式的起源,我們看下面的圖:

 介面卡模式將某個類的介面轉換成客戶端期望的另一個介面表示,目的是消除由於介面不匹配所造成的類的相容性問題。主要分為三類:類的介面卡模式、物件的介面卡模式、介面的介面卡模式。首先,我們來看看類的介面卡模式,先看類圖:

核心思想就是:有一個Source類,擁有一個方法,待適配,目標介面時Targetable,通過Adapter類,將Source的功能擴充套件到Targetable裡,看程式碼:

  1. public class Source {  
  2.   
  3.     public void method1() {  
  4.         System.out.println("this is original method!");  
  5.     }  
  6. }  
  1. public interface Targetable {  
  2.   
  3.     /* 與原類中的方法相同 */  
  4.     public void method1();  
  5.   
  6.     /* 新類的方法 */  
  7.     public void method2();  
  8. }  
  1. public class Adapter extends Source implements Targetable {  
  2.   
  3.     @Override  
  4.     public void method2() {  
  5.         System.out.println("this is the targetable method!");  
  6.     }  
  7. }  

Adapter類繼承Source類,實現Targetable介面,下面是測試類:

  1. public class AdapterTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Targetable target = new Adapter();  
  5.         target.method1();  
  6.         target.method2();  
  7.     }  
  8. }  

輸出:

this is original method!
this is the targetable method!

這樣Targetable介面的實現類就具有了Source類的功能。

物件的介面卡模式

基本思路和類的介面卡模式相同,只是將Adapter類作修改,這次不繼承Source類,而是持有Source類的例項,以達到解決相容性的問題。看圖:

 

只需要修改Adapter類的原始碼即可:

  1. public class Wrapper implements Targetable {  
  2.   
  3.     private Source source;  
  4.       
  5.     public Wrapper(Source source){  
  6.         super();  
  7.         this.source = source;  
  8.     }  
  9.     @Override  
  10.     public void method2() {  
  11.         System.out.println("this is the targetable method!");  
  12.     }  
  13.   
  14.     @Override  
  15.     public void method1() {  
  16.         source.method1();  
  17.     }  
  18. }  

測試類:

  1. public class AdapterTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Source source = new Source();  
  5.         Targetable target = new Wrapper(source);  
  6.         target.method1();  
  7.         target.method2();  
  8.     }  
  9. }  

輸出與第一種一樣,只是適配的方法不同而已。

第三種介面卡模式是介面的介面卡模式,介面的介面卡是這樣的:有時我們寫的一個介面中有多個抽象方法,當我們寫該介面的實現類時,必須實現該介面的所有方法,這明顯有時比較浪費,因為並不是所有的方法都是我們需要的,有時只需要某一些,此處為了解決這個問題,我們引入了介面的介面卡模式,藉助於一個抽象類,該抽象類實現了該介面,實現了所有的方法,而我們不和原始的介面打交道,只和該抽象類取得聯絡,所以我們寫一個類,繼承該抽象類,重寫我們需要的方法就行。看一下類圖:

這個很好理解,在實際開發中,我們也常會遇到這種介面中定義了太多的方法,以致於有時我們在一些實現類中並不是都需要。看程式碼:

  1. public interface Sourceable {  
  2.       
  3.     public void method1();  
  4.     public void method2();  
  5. }  

抽象類Wrapper2:

  1. public abstract class Wrapper2 implements Sourceable{  
  2.       
  3.     public void method1(){}  
  4.     public void method2(){}  
  5. }  
  1. public class SourceSub1 extends Wrapper2 {  
  2.     public void method1(){  
  3.         System.out.println("the sourceable interface's first Sub1!");  
  4.     }  
  5. }  
  1. public class SourceSub2 extends Wrapper2 {  
  2.     public void method2(){  
  3.         System.out.println("the sourceable interface's second Sub2!");  
  4.     }  
  5. }  
  1. public class WrapperTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Sourceable source1 = new SourceSub1();  
  5.         Sourceable source2 = new SourceSub2();  
  6.           
  7.         source1.method1();  
  8.         source1.method2();  
  9.         source2.method1();  
  10.         source2.method2();  
  11.     }  
  12. }  

測試輸出:

the sourceable interface's first Sub1!
the sourceable interface's second Sub2!

達到了我們的效果!

 講了這麼多,總結一下三種介面卡模式的應用場景:

類的介面卡模式:當希望將一個類轉換成滿足另一個新介面的類時,可以使用類的介面卡模式,建立一個新類,繼承原有的類,實現新的介面即可。

物件的介面卡模式:當希望將一個物件轉換成滿足另一個新介面的物件時,可以建立一個Wrapper類,持有原類的一個例項,在Wrapper類的方法中,呼叫例項的方法就行。

介面的介面卡模式:當不希望實現一個介面中所有的方法時,可以建立一個抽象類Wrapper,實現所有方法,我們寫別的類的時候,繼承抽象類即可。

7、裝飾模式(Decorator)

顧名思義,裝飾模式就是給一個物件增加一些新的功能,而且是動態的,要求裝飾物件和被裝飾物件實現同一個介面,裝飾物件持有被裝飾物件的例項,關係圖如下:

Source類是被裝飾類,Decorator類是一個裝飾類,可以為Source類動態的新增一些功能,程式碼如下:

  1. public interface Sourceable {  
  2.     public void method();  
  3. }  
  1. public class Source implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("the original method!");  
  6.     }  
  7. }  
  1. public class Decorator implements Sourceable {  
  2.   
  3.     private Sourceable source;  
  4.       
  5.     public Decorator(Sourceable source){  
  6.         super();  
  7.         this.source = source;  
  8.     }  
  9.     @Override  
  10.     public void method() {  
  11.         System.out.println("before decorator!");  
  12.         source.method();  
  13.         System.out.println("after decorator!");  
  14.     }  
  15. }  

測試類:

  1. public class DecoratorTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Sourceable source = new Source();  
  5.         Sourceable obj = new Decorator(source);  
  6.         obj.method();  
  7.     }  
  8. }  

輸出:

before decorator!
the original method!
after decorator!

裝飾器模式的應用場景:

1、需要擴充套件一個類的功能。

2、動態的為一個物件增加功能,而且還能動態撤銷。(繼承不能做到這一點,繼承的功能是靜態的,不能動態增刪。)

缺點:產生過多相似的物件,不易排錯!

8、代理模式(Proxy)

其實每個模式名稱就表明了該模式的作用,代理模式就是多一個代理類出來,替原物件進行一些操作,比如我們在租房子的時候回去找中介,為什麼呢?因為你對該地區房屋的資訊掌握的不夠全面,希望找一個更熟悉的人去幫你做,此處的代理就是這個意思。再如我們有的時候打官司,我們需要請律師,因為律師在法律方面有專長,可以替我們進行操作,表達我們的想法。先來看看關係圖:

 

根據上文的闡述,代理模式就比較容易的理解了,我們看下程式碼:

  1. public interface Sourceable {  
  2.     public void method();  
  3. }  
  1. public class Source implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("the original method!");  
  6.     }  
  7. }  
  1. public class Proxy implements Sourceable {  
  2.   
  3.     private Source source;  
  4.     public Proxy(){  
  5.         super();  
  6.         this.source = new Source();  
  7.     }  
  8.     @Override  
  9.     public void method() {  
  10.         before();  
  11.         source.method();  
  12.         atfer();  
  13.     }  
  14.     private void atfer() {  
  15.         System.out.println("after proxy!");  
  16.     }  
  17.     private void before() {  
  18.         System.out.println("before proxy!");  
  19.     }  
  20. }  

測試類:

  1. public class ProxyTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Sourceable source = new Proxy();  
  5.         source.method();  
  6.     }  
  7.   
  8. }  

輸出:

before proxy!
the original method!
after proxy!

代理模式的應用場景:

如果已有的方法在使用的時候需要對原有的方法進行改進,此時有兩種辦法:

1、修改原有的方法來適應。這樣違反了“對擴充套件開放,對修改關閉”的原則。

2、就是採用一個代理類呼叫原有的方法,且對產生的結果進行控制。這種方法就是代理模式。

使用代理模式,可以將功能劃分的更加清晰,有助於後期維護!

9、外觀模式(Facade)

外觀模式是為了解決類與類之家的依賴關係的,像spring一樣,可以將類和類之間的關係配置到配置檔案中,而外觀模式就是將他們的關係放在一個Facade類中,降低了類類之間的耦合度,該模式中沒有涉及到介面,看下類圖:(我們以一個計算機的啟動過程為例)

我們先看下實現類:

  1. public class CPU {  
  2.       
  3.     public void startup(){  
  4.         System.out.println("cpu startup!");  
  5.     }  
  6.       
  7.     public void shutdown(){  
  8.         System.out.println("cpu shutdown!");  
  9.     }  
  10. }  
  1. public class Memory {  
  2.       
  3.     public void startup(){  
  4.         System.out.println("memory startup!");  
  5.     }  
  6.       
  7.     public void shutdown(){  
  8.         System.out.println("memory shutdown!");  
  9.     }  
  10. }  
  1. public class Disk {  
  2.       
  3.     public void startup(){  
  4.         System.out.println("disk startup!");  
  5.     }  
  6.       
  7.     public void shutdown(){  
  8.         System.out.println("disk shutdown!");  
  9.     }  
  10. }  
  1. public class Computer {  
  2.     private CPU cpu;  
  3.     private Memory memory;  
  4.     private Disk disk;  
  5.       
  6.     public Computer(){  
  7.         cpu = new CPU();  
  8.         memory = new Memory();  
  9.         disk = new Disk();  
  10.     }  
  11.       
  12.     public void startup(){  
  13.         System.out.println("start the computer!");  
  14.         cpu.startup();  
  15.         memory.startup();  
  16.         disk.startup();  
  17.         System.out.println("start computer finished!");  
  18.     }  
  19.       
  20.     public void shutdown(){  
  21.         System.out.println("begin to close the computer!");  
  22.         cpu.shutdown();  
  23.         memory.shutdown();  
  24.         disk.shutdown();  
  25.         System.out.println("computer closed!");  
  26.     }  
  27. }  

User類如下:

  1. public class User {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Computer computer = new Computer();  
  5.         computer.startup();  
  6.         computer.shutdown();  
  7.     }  
  8. }  

輸出:

start the computer!
cpu startup!
memory startup!
disk startup!
start computer finished!
begin to close the computer!
cpu shutdown!
memory shutdown!
disk shutdown!
computer closed!

如果我們沒有Computer類,那麼,CPU、Memory、Disk他們之間將會相互持有例項,產生關係,這樣會造成嚴重的依賴,修改一個類,可能會帶來其他類的修改,這不是我們想要看到的,有了Computer類,他們之間的關係被放在了Computer類裡,這樣就起到了解耦的作用,這,就是外觀模式!

10、橋接模式(Bridge)

橋接模式就是把事物和其具體實現分開,使他們可以各自獨立的變化。橋接的用意是:將抽象化與實現化解耦,使得二者可以獨立變化,像我們常用的JDBC橋DriverManager一樣,JDBC進行連線資料庫的時候,在各個資料庫之間進行切換,基本不需要動太多的程式碼,甚至絲毫不用動,原因就是JDBC提供統一介面,每個資料庫提供各自的實現,用一個叫做資料庫驅動的程式來橋接就行了。我們來看看關係圖:

實現程式碼:

先定義介面:

  1. public interface Sourceable {  
  2.     public void method();  
  3. }  

分別定義兩個實現類:

  1. public class SourceSub1 implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("this is the first sub!");  
  6.     }  
  7. }  
  1. public class SourceSub2 implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("this is the second sub!");  
  6.     }  
  7. }  

定義一個橋,持有Sourceable的一個例項:

  1. public abstract class Bridge {  
  2.     private Sourceable source;  
  3.   
  4.     public void method(){  
  5.         source.method();  
  6.     }  
  7.       
  8.     public Sourceable getSource() {  
  9.         return source;  
  10.     }  
  11.   
  12.     public void setSource(Sourceable source) {  
  13.         this.source = source;  
  14.     }  
  15. }  
  1. public class MyBridge extends Bridge {  
  2.     public void method(){  
  3.         getSource().method();  
  4.     }  
  5. }  

測試類:

  1. public class BridgeTest {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         Bridge bridge = new MyBridge();  
  6.           
  7.         /*呼叫第一個物件*/  
  8.         Sourceable source1 = new SourceSub1();  
  9.         bridge.setSource(source1);  
  10.         bridge.method();  
  11.           
  12.         /*呼叫第二個物件*/  
  13.         Sourceable source2 = new SourceSub2();  
  14.         bridge.setSource(source2);  
  15.         bridge.method();  
  16.     }  
  17. }  

output:

this is the first sub!
this is the second sub!

這樣,就通過對Bridge類的呼叫,實現了對介面Sourceable的實現類SourceSub1和SourceSub2的呼叫。接下來我再畫個圖,大家就應該明白了,因為這個圖是我們JDBC連線的原理,有資料庫學習基礎的,一結合就都懂了。

11、組合模式(Composite)

組合模式有時又叫部分-整體模式在處理類似樹形結構的問題時比較方便,看看關係圖:

直接來看程式碼:

  1. public class TreeNode {  
  2.       
  3.     private String name;  
  4.     private TreeNode parent;  
  5.     private Vector<TreeNode> children = new Vector<TreeNode>();  
  6.       
  7.     public TreeNode(String name){  
  8.         this.name = name;  
  9.     }  
  10.   
  11.     public String getName() {  
  12.         return name;  
  13.     }  
  14.   
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.   
  19.     public TreeNode getParent() {  
  20.         return parent;  
  21.     }  
  22.   
  23.     public void setParent(TreeNode parent) {  
  24.         this.parent = parent;  
  25.     }  
  26.       
  27.     //新增孩子節點  
  28.     public void add(TreeNode node){  
  29.         children.add(node);  
  30.     }  
  31.       
  32.     //刪除孩子節點  
  33.     public void remove(TreeNode node){  
  34.         children.remove(node);  
  35.     }  
  36.       
  37.     //取得孩子節點  
  38.     public Enumeration<TreeNode> getChildren(){  
  39.         return children.elements();  
  40.     }  
  41. }  
  1. public class Tree {  
  2.   
  3.     TreeNode root = null;  
  4.   
  5.     public Tree(String name) {  
  6.         root = new TreeNode(name);  
  7.     }  
  8.   
  9.     public static void main(String[] args) {  
  10.         Tree tree = new Tree("A");  
  11.         TreeNode nodeB = new TreeNode("B");  
  12.         TreeNode nodeC = new TreeNode("C");  
  13.           
  14.         nodeB.add(nodeC);  
  15.         tree.root.add(nodeB);  
  16.         System.out.println("build the tree finished!");  
  17.     }  
  18. }  

使用場景:將多個物件組合在一起進行操作,常用於表示樹形結構中,例如二叉樹,數等。

12、享元模式(Flyweight)

享元模式的主要目的是實現物件的共享,即共享池,當系統中物件多的時候可以減少記憶體的開銷,通常與工廠模式一起使用。

FlyWeightFactory負責建立和管理享元單元,當一個客戶端請求時,工廠需要檢查當前物件池中是否有符合條件的物件,如果有,就返回已經存在的物件,如果沒有,則建立一個新物件,FlyWeight是超類。一提到共享池,我們很容易聯想到Java裡面的JDBC連線池,想想每個連線的特點,我們不難總結出:適用於作共享的一些個物件,他們有一些共有的屬性,就拿資料庫連線池來說,url、driverClassName、username、password及dbname,這些屬性對於每個連線來說都是一樣的,所以就適合用享元模式來處理,建一個工廠類,將上述類似屬性作為內部資料,其它的作為外部資料,在方法呼叫時,當做引數傳進來,這樣就節省了空間,減少了例項的數量。

看個例子:

看下資料庫連線池的程式碼:

  1. public class ConnectionPool {  
  2.       
  3.     private Vector<Connection> pool;  
  4.       
  5.     /*公有屬性*/  
  6.     private String url = "jdbc:mysql://localhost:3306/test";  
  7.     private String username = "root";  
  8.     private String password = "root";  
  9.     private String driverClassName = "com.mysql.jdbc.Driver";  
  10.   
  11.     private int poolSize = 100;  
  12.     private static ConnectionPool instance = null;  
  13.     Connection conn = null;  
  14.   
  15.     /*構造方法,做一些初始化工作*/  
  16.     private ConnectionPool() {  
  17.         pool = new Vector<Connection>(poolSize);  
  18.   
  19.         for (int i = 0; i < poolSize; i++) {  
  20.             try {  
  21.                 Class.forName(driverClassName);  
  22.                 conn = DriverManager.getConnection(url, username, password);  
  23.                 pool.add(conn);  
  24.             } catch (ClassNotFoundException e) {  
  25.                 e.printStackTrace();  
  26.             } catch (SQLException e) {  
  27.                 e.printStackTrace();  
  28.             }  
  29.         }  
  30.     }  
  31.   
  32.     /* 返回連線到連線池 */  
  33.     public synchronized void release() {  
  34.         pool.add(conn);  
  35.     }  
  36.   
  37.     /* 返回連線池中的一個資料庫連線 */  
  38.     public synchronized Connection getConnection() {  
  39.         if (pool.size() > 0) {  
  40.             Connection conn = pool.get(0);  
  41.             pool.remove(conn);  
  42.             return conn;  
  43.         } else {  
  44.             return null;  
  45.         }  
  46.     }  
  47. }  
 
通過連線池的管理,實現了資料庫連線的共享,不需要每一次都重新建立連線,節省了資料庫重新建立的開銷,提升了系統的效能!本章講解了7種結構型模式,因為篇幅的問題,剩下的11種行為型模式下章繼續!

相關文章