vendredi 27 février 2015

Factory Method pattern vs composition

From GoF chapter about the Factory Method pattern:



Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.



The idea is to let subclasses decided which class to instantiate, and GoF's implementation of the idea, is to provide an abstract method in the superclass, that subclasses need to override, and thus providing their own instantiation logic.


What I don't understand is, why implementing it using an abstract method, and not using a class member which is the factory. I'll explain.


This is the GoF way:



public abstract class Creator {
public void doStuff() {
Product product = createProduct();
/* etc. */
}

public abstract Product createProduct();
}


Usage:



MyCreator myCreator = new Creator() {
@Override
public Product createProduct() {
return new MyProduct();
}
}

myCreator.doStuff();


But why bother with the subclassing, etc.? I suggest this approach:



public class Creator {
private Factory factory;

/* constructor */
public Creator(Factory factory) {
this.factory = factory;
}

public void doStuff() {
Product product = factory.createProduct();
/* etc. */
}
}


And this is how you use it:



MyFactory myFactory = new MyFactory();
Creator creator = new Creator(myFactory);
creator.doStuff();


So what is the benefit in GoF's approach? Why not composing the Factory into the Creator class instead of expressing it using an abstract method?


Aucun commentaire:

Enregistrer un commentaire