With the Factory Pattern we provide a clean way to instantiate an object unknown to us at the time of implementation. The only thing we know is the interface of the object with a set of predefined properties and methods we need to use.
- Download or browse the FactoryPattern project code on GitHub.
In this example we create a Food Factory from a configuration file setting. The factory provides us with the proper kind of food. A call to the Food’s EatIt method shows us a debug message stating the effect this food has on our body. Take a look at the class diagram.
In our application configuration file we provide the fully qualified type name for the factory we want to use. In this case we go for the FastFood Factory (be honnest).
<applicationSettings> <FactoryPatternTests.Properties.Settings> <setting name="FoodFactory" serializeAs="String"> <value> FactoryPattern.FoodFactories.FastFoodFactory </value> </setting> </FactoryPatternTests.Properties.Settings> </applicationSettings>
Let’s write a little test to see the factory pattern in action. In our test we have a method called CreateFoodFactory. This method uses the FoodFactory setting we provided in our app.config. Next we load the FoodFactory assembly by using some magic reflection. Finally we call CreateInstance on this assembly with our factory name. We return the result as an IFoodFactory.
In our main program we can now instantiate some Food Factory, let it create some Food and let us eat it. We do not know or have to know what kind of factory or food we create. We just call on the interfaces.
using System.Linq; using System.Reflection; using FactoryPattern.Food; using FactoryPattern.FoodFactories; using FactoryPatternTests.Properties; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FactoryPatternTests { [TestClass] public class FoodFactoryTests { [TestMethod] public void CreateSomeFood() { IFoodFactory factory = CreateFoodFactory(); IFood food = factory.CreateFood(); food.EatIt(); } private IFoodFactory CreateFoodFactory() { string factoryName = Settings.Default.FoodFactory.Trim(); Assembly assembly = Assembly.Load(factoryName.Split('.').First()); object instance = assembly.CreateInstance(factoryName); return (IFoodFactory) instance; } } }









