When to use Factory method pattern?

29,996

Solution 1

Although this isn't necessarily it's primary use, it's good for something where you have specialized instances of a class:

public ITax BuildNewSalesTax()
public ITax BuildNewValueAddedTax()

You need both methods to build a tax object, but you don't want to have to depend on using "new" everytime because the constructors may be complex. This way I encapsulate all of the changes into a single method that is clear to others for future maintenance.

Solution 2

Use a factory method (not abstract factory) when you want to reuse common functionality with different components.

Example: Imagine you have an M16 rifle. Something like this:

public class M16
{
    private Scope scope = new StandardScope();
    private SecondaryWeapon secondary = new Bayonet();
    private Camouflage camo = new DesertCamo();

    public double getMass()
    {
        // Add the mass of the gun to the mass of all the attachments.
    }

    public Point2D shootAtTarget(Point2D targetPosition)
    {
        // Very complicated calculation taking account of lots of variables such as
        // scope accuracy and gun weight.
    }
}

You may be satisfied with it for a while, thinking that you wont want to change anything. But then you have to do a secret nightime stealth mission in the jungle, and you realise that your attachments are completely inappropriate. You really need a NightVision scope, JungleCamo and a GrenadeLauncher secondary weapon. You will have to copy past the code from your original M16......not good extensibility.....Factory Method to the rescue!

Rewrite your M16 class:

public abstract class M16
{
    private Scope scope = getScope();
    private SecondaryWeapon secondary = getSecondaryWeapon();
    private Camouflage camo = getCamouflage();

    public double getMass()
    {
        // Add the mass of the gun to the mass of all the attachments.
    }

    public Point2D shootAtTarget(Point2D targetPosition)
    {
        // Very complicated calculation taking account of lots of variables such as
        // scope accuracy and gun weight.
    }

    // Don't have to be abstract if you want to have defaults.
    protected abstract Scope getScope();
    protected abstract SecondaryWeapon getSecondaryWeapon();
    protected abstract Camouflage getCamouflage();
}


//Then, your new JungleM16 can be created with hardly any effort (and importantly, no code //copying):

public class JungleM16 : M16
{
    public Scope getScope()
    {
        return new NightVisionScope();
    }

    public SecondaryWeapon getSecondaryWeapon()
    {
        return new GrenadeLauncher();
    }

    public Camouflage getCamouflage()
    {
        return new JungleCamo();
    }
}

Main idea? Customise and swap out composing objects while keeping common functionality.

An actually useful place to use it: You have just designed a really cool GUI, and it has a really complicated layout. It would be a real pain to have to layout everything again if you wanted to have different widgets. So.....use a factory method to create the widgets. Then, if you change your mind (or someone else want to use your class, but use different components) you can just subclass the GUI and override the factory methods.

Solution 3

I have two cases where I tend to use it:

  1. The object needs to be initialized in some specific manner
  2. When I want to construct a specific type based on an abstract type (an abstract class or an interface).

Examples:

  1. First case could be that you want to have a factory creating SqlCommand objects, where you automatically attach a valid SqlConnection before returning the command object.

  2. Second case is if you have an interface defined and determine at execution time which exact implementation of the interface to use (for instance by specifying it in a configuration file).

Solution 4

You can refer to section 9.5 Factories from Framework Design Guidelines 2nd Edition. Here is quoted set of guidelines with respect to using factories over constructors:

DO prefer constructors to factories, because they are generally more usable, consistent, and convenient than specialized construction mechanisms.

CONSIDER using a factory if you need more control than can be provided by constructors over the creation of the instances.

DO use a factory in cases where a developer might not know which type to construct, such as when coding against a base type or interface.

CONSIDER using a factory if having a named method is the only way to make the operation self-explanatory.

DO use a factory for conversion-style operations.

And from section 5.3 Constructor Design

CONSIDER using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construc- tion of a new instance, or if following the constructor design guidelines feels unnatural.

Solution 5

I am using Factory pattens when

  1. When a class does not know which class of objects it must create.

  2. A class specifies its sub-classes to specify which objects to create.

  3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.

Share:
29,996
Jaswant Agarwal
Author by

Jaswant Agarwal

Enjoying coding from last few years

Updated on February 13, 2020

Comments

  • Jaswant Agarwal
    Jaswant Agarwal over 4 years

    When to use Factory method pattern?

    Please provide me some specific idea when to use it in project? and how it is a better way over new keyword?

  • Owais Qureshi
    Owais Qureshi about 12 years
    Hey its a great explanation,Have you written any tutorials I wud love to read them..!
  • Fred
    Fred about 8 years
    I've worked in a code base where every "new" was replaced with a factory delegate, fully IoC Containered. It was a nightmare to work with. After a year and a half of development with 5 devs, it was scrapped. The functionality was replaced in 1 month by 3 devs using industry standard practices. From my experience, factories are very useful in the instances @Dzmitri pointed out. Unless you plan on switching out the type by configuration or have very interesting constructor logic, I think replacing new with factories is overkill and counterproductive.
  • Flavio
    Flavio almost 7 years
    Hey man, excellent explanation. It made a lot easier to understand. Good job.
  • Pue-Tsuâ
    Pue-Tsuâ over 2 years
    Finally a factory pattern that makes sense. I saw a lot of very bad examples that doesn't do any good to codebase.