A Dependency Problem


Astute readers will recognize a problem with this form of the FACTORY pattern. The class ShapeFactory has a method for each of the derivatives of Shape. This results in a name-only dependency that makes it difficult to add new derivatives to Shape. Every time we add a new Shape derivative, we have to add a new method to the ShapeFactory interface. In most cases, this means that we'll have to recompile and redeploy all the users of ShapeFactory.[1]

[1] Again, this isn't exactly necessary in C#. You might get away without recompiling and redeploying clients of a changed interface. But it's a risky business.

We can get rid of this dependency problem by sacrificing a little type safety. Instead of giving ShapeFactory one method for every Shape derivative, we can give it only one make function that takes a string. For example, look at Listing 29-3. This technique requires that ShapeFactoryImplementation use an if/else chain on the incoming argument to select which derivative of Shape to instantiate. This is shown in Listings 29-4 and 29-5.

Listing 29-3. A snippet that creates a circle

[Test] public void TestCreateCircle() {   Shape s = factory.Make("Circle");   Assert.IsTrue(s is Circle); }

Listing 29-4. ShapeFactory.cs

public interface ShapeFactory {   Shape Make(string name); }

Listing 29-5. ShapeFactoryImplementation.cs

public class ShapeFactoryImplementation : ShapeFactory {   public Shape Make(string name)   {     if(name.Equals("Circle"))       return new Circle();     else if(name.Equals("Square"))       return new Square();     else       throw new Exception(         "ShapeFactory cannot create: {0}", name);   } }

One might argue that this is dangerous, because callers who misspell the name of a shape will get a runtime error instead of a compile-time error. This is true. However, if you are writing the appropriate unit tests and are applying test-driven development, you'll catch these runtime errors long before they become problems.




Agile Principles, Patterns, and Practices in C#
Agile Principles, Patterns, and Practices in C#
ISBN: 0131857258
EAN: 2147483647
Year: 2006
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net