1. 程式人生 > >Java 設計模式 - 策略模式

Java 設計模式 - 策略模式

策略模式

定義一系列的演算法,把他們一個一個封裝起來, 是他們可以相互替換. 於是利用策略模式可以完成獨立於呼叫者而變化.

UML圖示

將實際演算法封裝成一個一個的類,並讓這些類繼承同一個介面. 在呼叫者中宣告這個物件的引用, 同時在使用時根據具體情況, 選擇不同實現類完成對該引用的實現.

策略模式舉例

- FirmAccountEnrichmentDelegate.java

public interface FirmAccountEnrichmentDelegate {

    public String getFirmAccount(Trade trade);
}

- BondFirmAccountEnrichmentDelegate.java

public class BondFirmAccountEnrichmentDelegate implements FirmAccountEnrichmentDelegate {
    @Override
    public String getFirmAccount(Trade trade) {
        return "Yards";
    }
}

- SwapFirmAccountEnrichmentDelegate.java

public class SwapFirmAccountEnrichmentDelegate implements FirmAccountEnrichmentDelegate {
    @Override
    public String getFirmAccount(Trade trade) {
        return "SMS2";
    }
}

- TradeEnrichment.java

public class TradeEnrichment {

    private Trade trade;
    private FirmAccountEnrichmentDelegate firmAccountEnrichmentDelegate;

    public TradeEnrichment(Trade trade){
        this.trade = trade;
    }

    public void enrichTrade(){
        if(trade.getTradeType().trim().equals("Bond")){
            firmAccountEnrichmentDelegate = new BondFirmAccountEnrichmentDelegate();
        }else{
            firmAccountEnrichmentDelegate = new SwapFirmAccountEnrichmentDelegate();
        }
        trade.setFirmAccount(firmAccountEnrichmentDelegate.getFirmAccount(trade));
        System.out.println("Trade is "+trade);
    }
}

- Trade.java

public class Trade {
    private String tradeType;
    private String firmAccount;

    public String getTradeType() {
        return tradeType;
    }

    public void setTradeType(String tradeType) {
        this.tradeType = tradeType;
    }

    public String getFirmAccount() {
        return firmAccount;
    }

    public void setFirmAccount(String firmAccount) {
        this.firmAccount = firmAccount;
    }

    @Override
    public String toString() {
        return "Trade{" +
                "tradeType='" + tradeType + '\'' +
                ", firmAccount='" + firmAccount + '\'' +
                '}';
    }
}

- Starter.java

public class Starter {

    public static void main(String[] args){
        Trade trade1 = new Trade();
        trade1.setTradeType("Bond");
        TradeEnrichment tradeEnrichment1 = new TradeEnrichment(trade1);
        tradeEnrichment1.enrichTrade();

        Trade trade2 = new Trade();
        trade2.setTradeType("Swap");
        TradeEnrichment tradeEnrichment2 = new TradeEnrichment(trade2);
        tradeEnrichment2.enrichTrade();
    }
}