Strategy and Flyweight patterns -
i've read "strategy objects make flyweights" (from design patterns elements of reusable object-oriented software), , i'm wondering how can implemented. didn't find example in internet.
is code (c#) below right, following idea?
thanks!
using system; using system.collections.generic; namespace strategyflyweight { class program { static void main(string[] args) { client client = new client(); for(int = 1; <= 10;i++) { client.execute(i); } console.readkey(); } } public interface istrategy { void check(int number); } public class concretestrategyeven : istrategy { public void check(int number) { console.writeline("{0} number...", number); } } public class concretestrategyodd : istrategy { public void check(int number) { console.writeline("{0} odd number...", number); } } public class flyweightfactory { private dictionary<string, istrategy> _sharedobjects = new dictionary<string, istrategy>(); public istrategy getobject(int param) { string key = (param % 2 == 0) ? "even" : "odd"; if (_sharedobjects.containskey(key)) return _sharedobjects[key]; else { istrategy strategy = null; switch (key) { case "even": strategy = new concretestrategyeven(); break; case "odd": strategy = new concretestrategyodd(); break; } _sharedobjects.add(key, strategy); return strategy; } } } public class client { private istrategy _strategy; private flyweightfactory _flyweightfactory = new flyweightfactory(); public void execute(int param) { changestrategy(param); _strategy.check(param); } private void changestrategy(int param) { _strategy = _flyweightfactory.getobject(param); } } }
i think implement flyweight pattern here, factory method should return same instance of particular strategy (like concretestrategyeven
) rather constructing new instance each time.
if i'm not mistaken, point of saying strategy objects make flyweights encapsulate no state (since represent algorithms rather entities) , can reused.
here link example of flyweight factory: http://www.java2s.com/code/java/design-pattern/flyweightfactory.htm. note 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 factory method, new flyweightintr
initialized if correct 1 not available; otherwise retrieved lstflyweight
.
Comments
Post a Comment