Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use a factory:</p> <pre><code>public class ImageFactory { Dictionary&lt;Type, Func&lt;IPerson, Image&gt;&gt; _creators; void Assign&lt;TPerson&gt;(Func&lt;IPerson, Image&gt; imageCreator) where T : IPerson { _creators.Add(typeof(TPerson), imageCreator); } void Create(Person person) { Func&lt;IPerson, Image&gt; creator; if (!_creators.TryGetValue(person.GetType(), out creator)) return null; return creator(person); } } </code></pre> <p>Assign factory methods:</p> <pre><code>imageFactory.Assign&lt;Man&gt;(person =&gt; new Image("Man"); imageFactory.Assign&lt;Woman&gt;(person =&gt; new Image("Big bad mommy"); imageFactory.Assign&lt;Mice&gt;(person =&gt; new Image("Tiny little mouse"); </code></pre> <p>And use it:</p> <pre><code>var imageOfSomeone = imageFactory.Create(man); var imageOfSomeone2 = imageFactory.Create(woman); var imageOfSomeone3 = imageFactory.Create(mice); </code></pre> <p>To be able to return different images for men you can use a condition:</p> <pre><code>factory.Assign&lt;Man&gt;(person =&gt; person.Age &gt; 10 ? new Image("Man") : new Image("Boy")); </code></pre> <p>For clarity you can add all more complex methods to a class:</p> <pre><code>public static class PersonImageBuilders { public static Image CreateMen(IPerson person) { if (person.Age &gt; 60) return new Image("Old and gready!"); else return new Image("Young and foolish!"); } } </code></pre> <p>And assign the method</p> <pre><code>imageFactory.Assign&lt;Man&gt;(PersonImageBuilders.CreateMen); </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