2009年8月7日 星期五

Design Pattern - Adapter Pattern

Adapter Pattern

看了良葛格詳細的說明, 原來pattern還是有區別用途
gof模式
Creational 模式
Structural 模式
Behavioral 模式

這裡提到的Adapter Pattern 屬於 Structural 模式, 是如何設計物件之間的靜態結構的一個解決方案

Adapter Pattern 有分為 Object Adapter 與 Class Adapter
而 Class Adapter是要運用在多重繼承上的, java不行直接多重繼承, 這裡不提

Adapter Pattern 與 Decorator Pattern 類似, 都是要把一些物件封裝起來

當你想銜接二個不同的接口時, 可以考慮這模式, 例如:

原本開發時, 假設client端(這裡假設程式是提供給別人用, 不能輕易的改code),
在實作時, 要取得客戶資料時, 都是對應到ICustomer介面,
但後來想要增加經銷商處理的功能時...

public interface ICustomer{
public String sync();
public String save();
}


實作客戶取資料的動作

public class Customer implements ICustomer{

public String sync(){
//客戶資料的同步
}
public String save(){
//客戶資料儲存
}
}


假設這個類別是提供給客戶使用的

public class BusinessLogic{

ICustomer customer;
Public BusinessLogic(ICustomer customer){
this.customer = customer;
}

public void syncCustomer(){
customer.sync();
}
public void saveCustomer(){
customer.save();
}
}


客戶實際操作商業邏輯時

public class DemoClients{
public static void main(String[] args){
//logic
Customer c = new Customer(); //要處理customer資料時
BusinessLogic bl = new BusinessLogic(c);
bl.syncCustomer();
bl.saveCustomer();
}
}


但現在突然想加入經銷商的一些處理時, 但要處理的動作與ICustomer不同時,
可以寫個Adapter來中介


public interface IDealer{
public String buildXML();
public String save();
}

public class Dealer implements IDealer{
public String buildXML(){
//經銷商的實作xml
}
public String save(){
//經銷商的實作save
}
}


這裡是implemnts 原本的ICustomer介面, 所以對提供給user的BusinessLogic介面是相同的

public class DealerAdapter implements ICustomer{

private Dealer dealer;

public dealerAdapter(IDealer dealer){
this.dealer = dealer;
}

public String sync(){
dealer.sync();
}
public String save(){
dealer.save();
}
}


所以現在提供給user的BusinessLogic class不用動, 就可以加點東西

public class DemoNewClients{

public static void main(String[] args){

//logic
Customer c = new Customer(); //要處理customer資料時
BusinessLogic bl = new BusinessLogic(c);
bl.syncCustomer();
bl.saveCustomer();

//logic
Dealer dealer = new Dealer(); //當要處理dealer的資料時
DealerAdapter dealerAdapter = new DealerAdapter(dealer);
BusinessLogic bl = new BusinessLogic(dealerAdapter);
bl.syncCustomer(); //對user來講, 使用的接口是相同的, 但行為變了
bl.saveCustomer();
}
}

0 意見: