Does The Factory Method Stand the Test of Time?
Join the DZone community and get the full member experience.
Join For FreeDefine an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.
Here is some sample code:
public class MazeGame { public MazeGame() { Room room1 = MakeRoom(); Room room2 = MakeRoom(); room1.Connect(room2); AddRoom(room1); AddRoom(room2); } protected virtual Room MakeRoom() { return new OrdinaryRoom(); } }
This pattern is quite useful, and is in fairly moderate use. For example, you can take a look at WebClient.GetWebRequest, which is an exact implementation of this pattern. I like this pattern because this allows me to keep the Open Closed Principle, I don’t need to modify the class, I can just inherit and override it to change things.
Still, this is the class method. I like to mix things up a bit and not use a virtual method, instead, I do things like this:
public class MazeGame { public Func<Room> MakeRoom = () => new OrdinaryRoom(); }
This allows me change how we are creating the room without even having to create a new subclass. In fact, it allows me to change this per instance.
I make quite a heavy use of this in RavenDB, for example. The DocumentConventions class is basically built of nothing else.
Recommendation: Go for the lightweight Factory Delegate approach. As with all patterns, use with caution and watch for overuse & abuse. In particular, if you need to manage state between multiple delegate, fall back to the overriding approach, because you can keep the state in the subclass.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Guide To Selecting the Right GitOps Tool - Argo CD or Flux CD
-
DevOps Midwest: A Community Event Full of DevSecOps Best Practices
-
Clear Details on Java Collection ‘Clear()’ API
-
What Is JHipster?
Comments