23種設計模式全解析三

B、結構模式(7種)

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



6、適配器模式

 適配器模式將某個類的接口轉換成客戶端期望的另一個接口表示,目的是消除由於接口不匹配所造成的類的兼容性問題。主要分爲三類:類的適配器模式、對象的適配器模式、接口的適配器模式。

01、類的適配器模式

核心思想就是:有一個Source類,擁有一個方法,待適配,目標接口是Targetable,通過Adapter類,將Source的功能擴展到Targetable裏,看代碼:

[java] view plaincopy

  1. public class Source {  

  2.   

  3.     public void method1() {  

  4.         System.out.println("this is original method!");  

  5.     }  

  6. }  

[java] view plaincopy

  1. public interface Targetable {  

  2.   

  3.     /* 與原類中的方法相同 */  

  4.     public void method1();  

  5.   

  6.     /* 新類的方法 */  

  7.     public void method2();  

  8. }  

[java] view plaincopy

  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接口,下面是測試類:

[java] view plaincopy

  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類的功能。

02、對象的適配器模式

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

 

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

[java] view plaincopy

  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. }  

測試類:

[java] view plaincopy

  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. }  

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


03、接口的適配器模式

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

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

[java] view plaincopy

  1. public interface Sourceable {  

  2.       

  3.     public void method1();  

  4.     public void method2();  

  5. }  

抽象類Wrapper2:

[java] view plaincopy

  1. public abstract class Wrapper2 implements Sourceable{  

  2.       

  3.     public void method1(){}  

  4.     public void method2(){}  

  5. }  

[java] view plaincopy

  1. public class SourceSub1 extends Wrapper2 {  

  2.     public void method1(){  

  3.         System.out.println("the sourceable interface's first Sub1!");  

  4.     }  

  5. }  

[java] view plaincopy

  1. public class SourceSub2 extends Wrapper2 {  

  2.     public void method2(){  

  3.         System.out.println("the sourceable interface's second Sub2!");  

  4.     }  

  5. }  

[java] view plaincopy

  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類動態的添加一些功能,代碼如下:

[java] view plaincopy

  1. public interface Sourceable {  

  2.     public void method();  

  3. }  

[java] view plaincopy

  1. public class Source implements Sourceable {  

  2.   

  3.     @Override  

  4.     public void method() {  

  5.         System.out.println("the original method!");  

  6.     }  

  7. }  

[java] view plaincopy

  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. }  

測試類:

[java] view plaincopy

  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)

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

 

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

[java] view plaincopy

  1. public interface Sourceable {  

  2.     public void method();  

  3. }  

[java] view plaincopy

  1. public class Source implements Sourceable {  

  2.   

  3.     @Override  

  4.     public void method() {  

  5.         System.out.println("the original method!");  

  6.     }  

  7. }  

[java] view plaincopy

  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. }  

測試類:

[java] view plaincopy

  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類中,降低了類類之間的耦合度,該模式中沒有涉及到接口,看下類圖:(我們以一個計算機的啓動過程爲例)

我們先看下實現類:

[java] view plaincopy

  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. }  

[java] view plaincopy

  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. }  

[java] view plaincopy

  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. }  

[java] view plaincopy

  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類如下:

[java] view plaincopy

  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提供統一接口,每個數據庫提供各自的實現,用一個叫做數據庫驅動的程序來橋接就行了。我們來看看關係圖:

實現代碼:

先定義接口:

[java] view plaincopy

  1. public interface Sourceable {  

  2.     public void method();  

  3. }  

分別定義兩個實現類:

[java] view plaincopy

  1. public class SourceSub1 implements Sourceable {  

  2.   

  3.     @Override  

  4.     public void method() {  

  5.         System.out.println("this is the first sub!");  

  6.     }  

  7. }  

[java] view plaincopy

  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的一個實例:

[java] view plaincopy

  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. }  

[java] view plaincopy

  1. public class MyBridge extends Bridge {  

  2.     public void method(){  

  3.         getSource().method();  

  4.     }  

  5. }  

測試類:

[java] view plaincopy

  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)

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

直接來看代碼:

[java] view plaincopy

  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. }  

[java] view plaincopy

  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,這些屬性對於每個連接來說都是一樣的,所以就適合用享元模式來處理,建一個工廠類,將上述類似屬性作爲內部數據,其它的作爲外部數據,在方法調用時,當做參數傳進來,這樣就節省了空間,減少了實例的數量。

看個例子:

看下數據庫連接池的代碼:

[java] view plaincopy

  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. }  

 

通過連接池的管理,實現了數據庫連接的共享,不需要每一次都重新創建連接,節省了數據庫重新創建的開銷,提升了系統的性能!

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章