Factory Pattern deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The essence of this pattern is to define 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 sub classes.
Suppose your company is producing several types of devices such as home appliances, entertainment devices, office devices, work devices and so on. Each time you want to create a product you need to use “new” operator to create it. There are two disadvantages to it
- You have to use new operator for each object creation
- Client has to know all the available products before creating the object.
Using factory pattern we will ask factory class, in this case device factory to create object for us based on the device type we pass. Below is the factory pattern implementation code in c#
public class IDevice { } public class HomeDevices : IDevice { } public class EntertainmentDevices : IDevice { } public enum DeviceType { Home, Entertainment, Office } public class DeviceFactory { public IDevice CreateDeviceContext(DeviceType type) { IDevice deviceContext; switch (type) { case DeviceType.Home: default: deviceContext = new HomeDevices(); break; case DeviceType.Entertainment: deviceContext = new EntertainmentDevices(); break; case DeviceType.Office: deviceContext = new OfficeDevices(); break; } return deviceContext; } }