I\'ve read that \"Strategy objects often make good flyweights\" (from Design Patterns Elements of Reusable Object-Oriented Software), and I\'m wondering how can thi
I think that to properly implement the flyweight pattern here, your factory method should always return the same instance of a particular strategy (like ConcreteStrategyEven
) rather than constructing a new instance each time.
If I'm not mistaken, the point of saying that Strategy objects make good Flyweights is that they often encapsulate no state (since they represent algorithms rather than entities) and can be reused.
Here is a link to an example of a Flyweight factory: http://www.java2s.com/Code/Java/Design-Pattern/FlyweightFactory.htm. Note this part, in particular:
public synchronized FlyweightIntr getFlyweight(String divisionName) {
if (lstFlyweight.get(divisionName) == null) {
FlyweightIntr fw = new Flyweight(divisionName);
lstFlyweight.put(divisionName, fw);
return fw;
} else {
return (FlyweightIntr) lstFlyweight.get(divisionName);
}
}
Here in the factory method, a new FlyweightIntr
is only initialized if the correct one is not available; otherwise it is retrieved from lstFlyweight
.