Java設計模式——結構型模式
Java設計模式中共有7種結構型模式:適配器模式、裝飾模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。其中對象的適配器模式是各種模式的起源,其關系如下面的圖:
1、適配器模式
適配器模式將某個類的接口轉換成客戶端期望的另一個接口表示,目的是消除由于接口不匹配所造成的類的兼容性問題。主要分為三類:類的適配器模式、對象的適配器模式、接口的適配器模式。
(1)類的適配器模式
核心思想就是:有一個Source類,其擁有一個方法method1,待適配,目標接口時Targetable,通過Adapter類(繼承Source類,實現Targetable接口),從而將Source的功能(method1方法)擴展到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 {
@Override
public 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類的功能。
應用場景:
當希望將一個類轉換成滿足另一個新接口(一個接口就代表一個功能"able")的類時,可以使用類的適配器模式,創建一個新類,繼承原有的類,實現新的接口即可。
在本例中即:我們希望Source 類能轉換成滿足Targetable 的功能()的Adapter 類,則可以將Adapter 類來繼承Source 類同時實現Targetable的接口。
(2)對象的適配器模式
基本思路和類的適配器模式相同,只是將Adapter類作修改,這次不繼承Source類,而是持有Source類的實例,以達到解決兼容性的問題。
public class Wrapper implements Targetable {
private Source source;
public Wrapper(Source source){
super();
this.source = source;
}
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
@Override
public 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();
}
}
輸出與第一種一樣,只是適配的方法不同而已。
應用場景:
當希望將一個對象轉換成滿足另一個新接口的對象時,可以創建一個Wrapper類,持有原類的一個實例,在Wrapper類的方法中,調用實例的方法就行。
(3)接口的適配器模式
有時我們寫的一個接口中有多個抽象方法,當我們寫該接口的實現類時,必須實現該接口的所有方法,這明顯有時比較浪費,因為并不是所有的方法都是我們需要的,有時只需要某一些,此處為了解決這個問題,我們引入了接口的適配器模式,借助于一個抽象類,該抽象類實現了該接口,實現了所有的方法,而我們不和原始的接口打交道,只和該抽象類取得聯系,所以我們寫一個類,繼承該抽象類,重寫我們需要的方法就行。
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,實現所有方法,我們寫別的類的時候,繼承抽象類即可。
2、裝飾模式(Decorator)
顧名思義,裝飾模式就是動態的給一個對象增加一些新的功能,要求裝飾對象和被裝飾對象實現同一個接口,裝飾對象持有被裝飾對象的實例(這就是裝飾的具體操作),關系圖如下:
Source類是被裝飾類,Decorator類是一個裝飾類,可以為Source類動態的添加一些功能,代碼如下:
public interface Sourceable {
public void method();
}
public class Source implements Sourceable {
@Override
public void method() {
System.out.println("the original method!");
}
}
public class Decorator implements Sourceable {
private Sourceable source;
public Decorator(Sourceable source){
super();
this.source = source;
}
@Override
public 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)、動態的為一個對象增加功能,而且還能動態撤銷。(繼承不能做到這一點,繼承的功能是靜態的,不能動態增刪。)
缺點:產生過多相似的對象,不易排錯!
3、代理模式(Proxy)
代理模式就是多一個代理類出來,替原對象進行一些操作,比如我們在租房子的時候回去找中介,為什么呢?因為你對該地區房屋的信息掌握的不夠全面,希望找一個更熟悉的人去幫你做,此處的代理就是這個意思。再如我們有的時候打官司,我們需要請律師,因為律師在法律方面有專長,可以替我們進行操作,表達我們的想法。先來看看關系圖:
public interface Sourceable {
public void method();
}
public class Source implements Sourceable {
@Override
public void method() {
System.out.println("the original method!");
}
}
public class Proxy implements Sourceable {
private Source source;
public Proxy(){
super();
this.source = new Source();
}
@Override
public 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、就是采用一個代理類調用原有的方法,且對產生的結果進行控制。這種方法就是代理模式。
使用代理模式,可以將功能劃分的更加清晰,有助于后期維護!
對比下裝飾模式和代理模式,其實在其內在邏輯是一樣的,它們都是通過持有目標實例對象來動態地給目標對象增加功能。
4、外觀模式(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類里,這樣就起到了解耦的作用。
5、橋接模式(Bridge)
橋接模式就是把事物和其具體實現分開,使他們可以各自獨立的變化。橋接的用意是:將抽象化與實現化解耦,使得二者可以獨立變化,像我們常用的JDBC橋DriverManager一樣,JDBC進行連接數據庫的時候,在各個數據庫之間進行切換,基本不需要動太多的代碼,甚至絲毫不用動,原因就是JDBC提供統一接口,每個數據庫提供各自的實現,用一個叫做數據庫驅動的程序DriverManager來橋接就行了。我們來看看關系圖:
public interface Sourceable {
public void method();
}
分別定義兩個實現類:
public class SourceSub1 implements Sourceable {
@Override
public void method() {
System.out.println("this is the first sub!");
}
}
public class SourceSub2 implements Sourceable {
@Override
public 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連接的原理,有數據庫學習基礎的,一結合就都懂了。
其中DriverManager就是橋,這個橋持有Driver這個接口的實例,同時Client客戶端再實例化DriverManager對象,完成橋接。
6、組合模式(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!");
}
}
應用場景:
將多個對象組合在一起進行操作,常用于表示樹形結構中,例如二叉樹,數等。
7、享元模式(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;
}
}
}
通過連接池的管理,實現了數據庫連接的共享,不需要每一次都重新創建連接,節省了數據庫重新創建的開銷,提升了系統的性能。
Java設計模式中結構型模式的7種設計模式全部講完,再來回顧下文章剛開始的這7種模式的關系圖,是不是更清晰了?
共同學習,寫下你的評論
評論加載中...
相關文章推薦