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]
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
Listing 29-4. ShapeFactory.cs
Listing 29-5. ShapeFactoryImplementation.cs
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. |