Note that there are some explanatory texts on larger screens.

plurals
  1. POStrategy and Flyweight patterns
    text
    copied!<p>I've read that "Strategy objects often make good flyweights" (from <em>Design Patterns Elements of Reusable Object-Oriented Software</em>), and I'm wondering how can this be implemented. I didn't find any example in the Internet.</p> <p>Is the code (C#) below right, following this idea?</p> <p>Thanks!</p> <pre><code>using System; using System.Collections.Generic; namespace StrategyFlyweight { class Program { static void Main(string[] args) { Client client = new Client(); for(int i = 1; i &lt;= 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} is an even number...", number); } } public class ConcreteStrategyOdd : IStrategy { public void Check(int number) { Console.WriteLine("{0} is an odd number...", number); } } public class FlyweightFactory { private Dictionary&lt;string, IStrategy&gt; _sharedObjects = new Dictionary&lt;string, IStrategy&gt;(); 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); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload