Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Composite and Strategy

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

like image 651
eouti Avatar asked Oct 25 '25 20:10

eouti


1 Answers

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();
like image 132
SkyWalker Avatar answered Oct 28 '25 04:10

SkyWalker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!