综合与战略相结合 [英] Combining Composite and Strategy

查看:162
本文介绍了综合与战略相结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个例子,展示如何组合这2种设计模式(战略与综合)。我知道如何使用Strategy,但Composite对我来说还不够清楚,所以我看不出如何组合它们。有人有例子或smthg吗?

干杯

解决方案

好的,这是一种方法,蓝色(伪Java代码):

 界面TradingStrategy {
void buy();
void sell();
}

class HedgingLongTermStrategy实现TradingStrategy {
void buy(){/ * TODO:* /};
void sell(){/ * TODO:* /};
}

class HighFreqIntradayStrategy实现TradingStrategy {
void buy(){/ * TODO:* /};
void sell(){/ * TODO:* /};
}

class CompositeTradingStrategy扩展ArrayList&TradingStrategy>实施TradingStrategy {
void buy(){
for(TradingStrategy strategy:this){
strategy.buy();
}
}
void sell(){
for(TradingStrategy strategy:this){
strategy.sell();
}
}
}

//样本代码
TradingStrategy composite = new CompositeTradingStrategy();
composite.add(new HighFreqIntradayStrategy());
composite.add(new HedgingLongTermStrategy());
composite.buy();


I am looking for an example showing how to combine this 2 design patterns (Strategy and Composite). I know how to use Strategy, but Composite is not enough clear for me, so I can't really see how to combine them. Does someone have example or smthg?
Cheers

解决方案

ok this is a way to do that out of the blue (in pseudo Java code):

interface TradingStrategy {
    void buy();
    void sell();   
}

class HedgingLongTermStrategy implements TradingStrategy {
    void buy() { /* TODO: */ };
    void sell() { /* TODO: */ };   
}

class HighFreqIntradayStrategy implements TradingStrategy {
    void buy() { /* TODO: */ };
    void sell() { /* TODO: */ };   
}

class CompositeTradingStrategy extends ArrayList<TradingStrategy> implements TradingStrategy {
    void buy() {
       for (TradingStrategy strategy : this) {
           strategy.buy();
       }
    }
    void sell() {
       for (TradingStrategy strategy : this) {
           strategy.sell();
       }
    }
}

// sample code
TradingStrategy composite = new CompositeTradingStrategy();
composite.add(new HighFreqIntradayStrategy());  
composite.add(new HedgingLongTermStrategy());
composite.buy();

这篇关于综合与战略相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆