Java之美[從菜鳥到高手演變]之設計模式二

來源:互聯網
上載者:User

在閱讀過程中有任何問題,請及時聯絡:egg。

郵箱:xtfggef@gmail.com 微博:http://weibo.com/xtfggef

如有轉載,請說明出處:http://blog.csdn.net/zhangerqing

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

6、適配器模式(Adapter)

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

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

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

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

public class AdapterTest {public static void main(String[] args) {Targetable target = new Adapter();target.method1();target.method2();}}

輸出:

this is original method!
this is the targetable method!

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

對象的適配器模式

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

 

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

public class Wrapper implements Targetable {private Source source;public Wrapper(Source source){super();this.source = source;}@Overridepublic void method2() {System.out.println("this is the targetable method!");}@Overridepublic void method1() {source.method1();}}

測試類別:

public class AdapterTest {public static void main(String[] args) {Source source = new Source();Targetable target = new Wrapper(source);target.method1();target.method2();}}

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

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

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

public interface Sourceable {public void method1();public void method2();}

抽象類別Wrapper2:

public abstract class Wrapper2 implements Sourceable{public void method1(){}public void method2(){}}
public class SourceSub1 extends Wrapper2 {public void method1(){System.out.println("the sourceable interface's first Sub1!");}}
public class SourceSub2 extends Wrapper2 {public void method2(){System.out.println("the sourceable interface's second Sub2!");}}
public class WrapperTest {public static void main(String[] args) {Sourceable source1 = new SourceSub1();Sourceable source2 = new SourceSub2();source1.method1();source1.method2();source2.method1();source2.method2();}}

測試輸出:

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

達到了我們的效果!

 講了這麼多,總結一下三種適配器模式的應用情境:

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

對象的適配器模式:當希望將一個對象轉換成滿足另一個新介面的對象時,可以建立一個Wrapper類,持有原類的一個執行個體,在Wrapper類的方法中,調用執行個體的方法就行。

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

7、裝飾模式(Decorator)

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

Source類是被裝飾類,Decorator類是一個裝飾類,可以為Source類動態添加一些功能,代碼如下:

public interface Sourceable {public void method();}
public class Source implements Sourceable {@Overridepublic void method() {System.out.println("the original method!");}}
public class Decorator implements Sourceable {private Sourceable source;public Decorator(Sourceable source){super();this.source = source;}@Overridepublic void method() {System.out.println("before decorator!");source.method();System.out.println("after decorator!");}}

測試類別:

public class DecoratorTest {public static void main(String[] args) {Sourceable source = new Source();Sourceable obj = new Decorator(source);obj.method();}}

輸出:

before decorator!
the original method!
after decorator!

裝飾器模式的應用情境:

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

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

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

8、代理模式(Proxy)

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

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

public interface Sourceable {public void method();}
public class Source implements Sourceable {@Overridepublic void method() {System.out.println("the original method!");}}
public class Proxy implements Sourceable {private Source source;public Proxy(){super();this.source = new Source();}@Overridepublic void method() {before();source.method();atfer();}private void atfer() {System.out.println("after proxy!");}private void before() {System.out.println("before proxy!");}}

測試類別:

public class ProxyTest {public static void main(String[] args) {Sourceable source = new Proxy();source.method();}}

輸出:

before proxy!
the original method!
after proxy!

代理模式的應用情境:

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

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

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

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

9、面板模式(Facade)

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

我們先看下實作類別:

public class CPU {public void startup(){System.out.println("cpu startup!");}public void shutdown(){System.out.println("cpu shutdown!");}}
public class Memory {public void startup(){System.out.println("memory startup!");}public void shutdown(){System.out.println("memory shutdown!");}}
public class Disk {public void startup(){System.out.println("disk startup!");}public void shutdown(){System.out.println("disk shutdown!");}}
public class Computer {private CPU cpu;private Memory memory;private Disk disk;public Computer(){cpu = new CPU();memory = new Memory();disk = new Disk();}public void startup(){System.out.println("start the computer!");cpu.startup();memory.startup();disk.startup();System.out.println("start computer finished!");}public void shutdown(){System.out.println("begin to close the computer!");cpu.shutdown();memory.shutdown();disk.shutdown();System.out.println("computer closed!");}}

User類如下:

public class User {public static void main(String[] args) {Computer computer = new Computer();computer.startup();computer.shutdown();}}

輸出:

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

實現代碼:

先定義介面:

public interface Sourceable {public void method();}

分別定義兩個實作類別:

public class SourceSub1 implements Sourceable {@Overridepublic void method() {System.out.println("this is the first sub!");}}
public class SourceSub2 implements Sourceable {@Overridepublic void method() {System.out.println("this is the second sub!");}}

定義一個橋,持有Sourceable的一個執行個體:

public abstract class Bridge {private Sourceable source;public void method(){source.method();}public Sourceable getSource() {return source;}public void setSource(Sourceable source) {this.source = source;}}
public class MyBridge extends Bridge {public void method(){getSource().method();}}

測試類別:

public class BridgeTest {public static void main(String[] args) {Bridge bridge = new MyBridge();/*調用第一個對象*/Sourceable source1 = new SourceSub1();bridge.setSource(source1);bridge.method();/*調用第二個對象*/Sourceable source2 = new SourceSub2();bridge.setSource(source2);bridge.method();}}

output:

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

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

11、組合模式(Composite)

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

直接來看代碼:

public class TreeNode {private String name;private TreeNode parent;private Vector<TreeNode> children = new Vector<TreeNode>();public TreeNode(String name){this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public TreeNode getParent() {return parent;}public void setParent(TreeNode parent) {this.parent = parent;}//添加孩子節點public void add(TreeNode node){children.add(node);}//刪除孩子節點public void remove(TreeNode node){children.remove(node);}//取得孩子節點public Enumeration<TreeNode> getChildren(){return children.elements();}}
public class Tree {TreeNode root = null;public Tree(String name) {root = new TreeNode(name);}public static void main(String[] args) {Tree tree = new Tree("A");TreeNode nodeB = new TreeNode("B");TreeNode nodeC = new TreeNode("C");nodeB.add(nodeC);tree.root.add(nodeB);System.out.println("build the tree finished!");}}

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

12、享元模式(Flyweight)

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

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

看個例子:

看下資料庫連接池的代碼:

public class ConnectionPool {private Vector<Connection> pool;/*公有屬性*/private String url = "jdbc:mysql://localhost:3306/test";private String username = "root";private String password = "root";private String driverClassName = "com.mysql.jdbc.Driver";private int poolSize = 100;private static ConnectionPool instance = null;Connection conn = null;/*構造方法,做一些初始化工作*/private ConnectionPool() {pool = new Vector<Connection>(poolSize);for (int i = 0; i < poolSize; i++) {try {Class.forName(driverClassName);conn = DriverManager.getConnection(url, username, password);pool.add(conn);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}}/* 返回串連到串連池 */public synchronized void release() {pool.add(conn);}/* 返回串連池中的一個資料庫連接 */public synchronized Connection getConnection() {if (pool.size() > 0) {Connection conn = pool.get(0);pool.remove(conn);return conn;} else {return null;}}}

通過串連池的管理,實現了資料庫連接的共用,不需要每一次都重新建立串連,節省了資料庫重新建立的開銷,提升了系統的效能!本章講解了7種結構型模式,因為篇幅的問題,剩下的11種行為型模式,我們將另起篇章,敬請讀者朋友們持續關注!

有問題請聯絡egg:

email:xtfggef@gmail.com    微博:http://weibo.com/xtfggef

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.