c# – Why is a factory method needed?


Let's say there is such an implementation of the factory method:

abstract class Creator
        public abstract Product FactoryMethod();

    class ConcreteCreatorA : Creator
        public override Product FactoryMethod() { return new ConcreteProductA(); }

    abstract class Product

    class ConcreteProductA : Product

What is the benefit to us of creating an object through the Creator , if you can create it in the same way through new ? When should you use the factory method, and what advantage can it give us?


There can be many benefits. Some:

  1. You can give a name to your constructor. For instance:

     Point PointCreator.FromPolar(double r, double phi)

    PointCreator.FromPolar reads much better than new Point(1, 0) .

  2. Since you are giving a name, you can have multiple constructors with the same signature:

     Point PointCreator.FromPolar(double r, double phi) { ... } Point PointCreator.FromCartesian(double x, double y) { ... }

    or for example

     DateTime DateTime.FromSeconds(double seconds) { ... } DateTime DateTime.FromMilliseconds(double ms) { ... }
  3. You can create objects not of this type, but of any derivative, and the specific type can be hidden inside the factory (so that your rest of the code will not depend on this specific type).

  4. You can take additional steps after the final construction of the object. For example, you can register an object in the list of all active objects. With a constructor, this is not very convenient, because you have to do it either in the constructor of the base class, and post a reference to an incompletely constructed object (which can lead to understandable problems if someone at this moment refers to the object), or duplicate the code in all descendants (which is not always possible and unverifiable, so it provokes bugs).

    Or you can do additional initialization of object properties if you need it:

     WebRequest InitWebRequest(string uri) { var request = WebRequest.Create(uri); request.Credentials = new NetworkCredential(Settings.Login, Settings.Password); return request; }
  5. You cannot make a constructor asynchronous, but you can make a factory method. In the factory method itself, you can call the constructor and the async method to initialize.

     async SerialDevice Create(PortInfo portInfo) { var device = new SerialDevice(portInfo); await device.Connect(); return device; }
Scroll to Top