<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Blog of Zachary Snow &#187; design-patterns</title>
	<atom:link href="http://zacharysnow.net/tag/design-patterns-2/feed/" rel="self" type="application/rss+xml" />
	<link>http://zacharysnow.net</link>
	<description></description>
	<lastBuildDate>Tue, 20 Dec 2011 19:41:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Marker Interfaces</title>
		<link>http://zacharysnow.net/2011/05/24/marker-interfaces/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=marker-interfaces</link>
		<comments>http://zacharysnow.net/2011/05/24/marker-interfaces/#comments</comments>
		<pubDate>Tue, 24 May 2011 19:05:33 +0000</pubDate>
		<dc:creator>Zachary</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[design-patterns]]></category>
		<category><![CDATA[empty-interface]]></category>
		<category><![CDATA[marker-interfaces]]></category>

		<guid isPermaLink="false">http://zacharysnow.net/?p=401</guid>
		<description><![CDATA[In Snowball I was debating adding an empty interface to identify certain classes in my framework as components. I wasn&#8217;t sure if this was code smell or not so I did some searching on Stackoverflow and found out this concept &#8230; <a href="http://zacharysnow.net/2011/05/24/marker-interfaces/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In Snowball I was debating adding an empty interface to identify certain classes in my framework as components. I wasn&#8217;t sure if this was code smell or not so I did some searching on <a href="http://stackoverflow.com/search?q=marker+interface">Stackoverflow</a> and found out this concept is actually called &#8220;Marker Interfaces&#8221;. Learn something new every day.</p>
]]></content:encoded>
			<wfw:commentRss>http://zacharysnow.net/2011/05/24/marker-interfaces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Favoring Composition over Inheritance</title>
		<link>http://zacharysnow.net/2011/01/18/favoring-composition-over-inheritance/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=favoring-composition-over-inheritance</link>
		<comments>http://zacharysnow.net/2011/01/18/favoring-composition-over-inheritance/#comments</comments>
		<pubDate>Tue, 18 Jan 2011 18:17:21 +0000</pubDate>
		<dc:creator>Zachary</dc:creator>
				<category><![CDATA[Composition]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[composition-over-inheritance]]></category>
		<category><![CDATA[design-patterns]]></category>

		<guid isPermaLink="false">http://zacharysnow.net/?p=363</guid>
		<description><![CDATA[You may have heard the expression before &#8220;Favor Composition over Inheritance&#8221;, but do you know what it means and how to apply it? Lets take this code for example: abstract class Car { public Color Color { get; protected set; &#8230; <a href="http://zacharysnow.net/2011/01/18/favoring-composition-over-inheritance/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>You may have heard the expression before &#8220;Favor Composition over Inheritance&#8221;, but do you know what it means and how to apply it? Lets take this code for example:</p>
<pre name="code" class="c#">
abstract class Car
{
	public Color Color { get; protected set; }
	public Engine Engine { get; protected set; }
}

class ElectricCar : Car
{
	public ElectricCar()
	{
		this.Color = Color.Blue;
		this.Engine = new ElectricEngine();
	}
}

class SportsCar : Car
{
	public SportsCar()
	{
		this.Color = Color.Red;
		this.Engine = new V8Engine();
	}
}

class Truck : Car
{
	public Truck()
	{
		this.Color = Color.White;
		this.Engine = new DieselEngine();
	}
}
</pre>
<p>In this contrived example, we&#8217;ve defined three types of cars. Each instance of each of the cars will always have the same color and same engine. What happens when we need a 4th type? We have to define another class. By refactoring this code, we can compose a car type by giving it a color and an engine:</p>
<pre name="code" class="c#">
class Car
{
	public Color Color { get; private set; }
	public Engine Engine { get; private set; }

	public Car(Color color, Engine engine)
	{
		this.Color = color;
		this.Engine = engine;
	}
}

Car electricCar = new Car(Color.Blue, new ElectricEngine());
Car sportsCar = new Car(Color.Red, new V8Engine());
Car truck = new Car(Color.White, new DieselEngine());
Car familyCar = new Car(Color.Black, new V4Engine());
</pre>
<p>Now we can compose many car types, with any combination of colors and engines and we&#8217;ve only defined one class.</p>
]]></content:encoded>
			<wfw:commentRss>http://zacharysnow.net/2011/01/18/favoring-composition-over-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing basic Dependency Injection using a Service Container</title>
		<link>http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=implementing-basic-dependency-injection-using-services-container</link>
		<comments>http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/#comments</comments>
		<pubDate>Mon, 21 Jun 2010 19:09:14 +0000</pubDate>
		<dc:creator>Zachary</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dependency-injection]]></category>
		<category><![CDATA[design-patterns]]></category>
		<category><![CDATA[service-continer]]></category>

		<guid isPermaLink="false">http://zacharysnow.net/?p=321</guid>
		<description><![CDATA[By extending your Service Container class, a very basic version of dependency injection can be implemented. We&#8217;ll implement two forms of dependency injection: constructor and property injection. We&#8217;ll start by defining the Injectable attribute. [AttributeUsage(AttributeTargets.Constructor &#124; AttributeTargets.Property, AllowMultiple = false, &#8230; <a href="http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>By extending your Service Container class, a very basic version of dependency injection can be implemented. We&#8217;ll implement two forms of dependency injection: constructor and property injection. </p>
<p><span id="more-321"></span></p>
<p>We&#8217;ll start by defining the <strong>Injectable</strong> attribute. </p>
<pre name="code" class="c#">
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Property,
	AllowMultiple = false, Inherited = true)]
public class InjectableAttribute : Attribute
{
}
</pre>
<p>We&#8217;ll use this attribute to mark our constructors and properties for dependency injection. Next we&#8217;ll define an interface for our dependency injector:</p>
<pre name="code" class="c#">
public interface IDependencyInjector
{
	T Construct&lt;T&gt;();
	void Inject(object instance);
}
</pre>
<p>We&#8217;ll define our service container like so:</p>
<pre name="code" class="c#">
public class ServiceContainer : IDependencyInjector, IServiceProvider
{
	Dictionary&lt;Type, Object&gt; services;

	public ServiceContainer()
		: base()
	{
		this.services = new Dictionary&lt;Type, object&gt;();
	}

	public void AddService(Type type, Object provider)
	{
		if(null == type)
			throw new ArgumentNullException("type");

		if(null == provider)
			throw new ArgumentNullException("provider");

		if(this.services.ContainsKey(type))
			throw new InvalidOperationException("A provider is already registered the type " + type);

		var providerType = provider.GetType();

		if(!type.IsAssignableFrom(providerType))
			throw new InvalidOperationException(providerType + " is not an instance of " + type);

		this.services.Add(type, provider);
	}

	public object GetService(Type type)
	{
		if(null == type)
			throw new ArgumentNullException("type");

		if(this.services.ContainsKey(type))
			return this.services[type];

		return null;
	}

	public void RemoveService(Type type)
	{
		if(null == type)
			throw new ArgumentNullException("type");

		this.services.Remove(type);
	}

	protected object GetInjectableService(Type type)
	{
		if(type == typeof(IDependencyInjector) ||
		   type == typeof(IServiceProvider))
		{
			return this;
		}
		else
		{
			object service = this.GetService(type);

			if(service == null)
				throw new InvalidOperationException("Failed to find " + type + " depenedency.");

			return service;
		}
	}

	public T Construct&lt;T&gt;()
	{
		ConstructorInfo injectableConstructor = null;
		foreach(ConstructorInfo constructor in typeof(T).GetConstructors())
		{
			foreach(Attribute attribute in constructor.GetCustomAttributes(true))
			{
				if(attribute is InjectableAttribute)
				{
					injectableConstructor = constructor;
					break;
				}
			}

			if(injectableConstructor != null)
				break;
		}

		if(injectableConstructor == null)
			throw new InvalidOperationException("No injectable constructor found.");

		var parameters = injectableConstructor.GetParameters();
		var services = new object[parameters.Length];

		int i = 0;
		foreach(ParameterInfo parameter in parameters)
			services[i++] = GetInjectableService(parameter.ParameterType);

		return (T)injectableConstructor.Invoke(services);
	}

	public void Inject(object instance)
	{
		foreach(PropertyInfo property in instance.GetType().GetProperties())
		{
			foreach(Attribute attribute in property.GetCustomAttributes(true))
			{
				if(attribute is InjectableAttribute)
				{
					if(!property.CanWrite)
						throw new InvalidOperationException(property.Name + " is marked as Injectable but not writable.");

					property.SetValue(instance, GetInjectableService(property.PropertyType), null);
				}
			}
		}
	}
}
</pre>
<p>You can now construct new instances and inject dependencies on existing instances. Some usage examples:</p>
<pre name="code" class="c#">
public interface IFoo
{
	int Value { get; }
}

public class Foo : IFoo
{
	public int Value
	{
		get;
		set;
	}

	[Injectable]
	public Foo()
	{
	}

	public void DoIt()
	{
		Console.WriteLine(this.Value);
	}
}

public interface IBar
{
	string Value { get; }
}

public class Bar : IBar
{
	IFoo foo;

	public string Value
	{
		get;
		set;
	}

	[Injectable]
	public Bar(IFoo foo)
	{
		this.foo = foo;
	}

	public void DoIt()
	{
		Console.WriteLine(this.Value + ": " + this.foo.Value);
	}
}

public class Baz
{
	[Injectable]
	public IFoo Foo
	{
		get;
		set;
	}

	[Injectable]
	public IBar Bar
	{
		get;
		set;
	}

	public void DoIt()
	{
		Console.WriteLine(this.Bar.Value + " | " + this.Foo.Value);
	}
}

class Program
{
	static void Main(string[] args)
	{
		var container = new ServiceContainer();

		var foo = container.Construct&lt;Foo&gt;();
		foo.Value = 5;
		container.AddService(typeof(IFoo), foo);

		var bar = container.Construct&lt;Bar&gt;();
		container.AddService(typeof(IBar), bar);
		bar.Value = "Hello World!";
		bar.DoIt();

		var baz = new Baz();
		container.Inject(baz);
		baz.DoIt();
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://zacharysnow.net/2010/06/21/implementing-basic-dependency-injection-using-services-container/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

