Type registry and the Factory Method

When implementing the Gofian Factory Method creational pattern it is normally the case that the client requiring the instance needs to tell the object factory what kind of object it needs to make. The internals of the factory method that decide what object to return usually resembles the following

public class Creator
public static IVehicle Create(VehicleType vehicleType)
IVehicle vehicle = new Chisasa();
vehicle = new Sedan();
vehicle = new FourByFour();

return vehicle;

This decision structure is easily refactored to an in-memory type registry which uses the lookup metaphor as demonstrated below:

private IDictionary<VehicleType,IVehicle> Vehicles
IDictionary<VehicleType,IVehicle> vehicles = new Dictionary<VehicleType,IVehicle>();
vehicles.Add(Vehicle.Sedan, new Sedan());
vehicles.Add(Vehicle.Mazembe, new Mazembe());
vehicles.Add(Vehicle.Chisasa, new Chisasa());
vehicles.Add(Vehicle.Chimbayambaya, new Chimbayambaya());
return vehicles;

public static IVehicle Find(VehicleType vehicleType)
return Vehicles[vehicleType];

If you are observant, you will notice that this changes the semantics of the implementation. We have now moved from creating objects to finding objects in a registry. Sound familiar? This emergent design shows us that the Factory Method is really a respository pattern in disguise. Refactoring a GOF pattern has teleported us to one of the basic tenets of Domain Driven Design, the Repository Pattern.

Some considerations to take into account would be deciding the best collection to use
to reduce the cost of lookup. It could also be possible to externalise the registry depending on the nature of the problem space.

No comments:

Purging Broadcom Drivers for Broadcom Wifi Card on Ubuntu sudo apt-get purge bcmwl-kernel-source   Reference: https://askubuntu.com/qu...