overexchange
overexchange

Reputation: 1

Advantage of factory method pattern

From wiki,

The Factory Method design pattern solves problems like:

  1. How can an object be created so that subclasses can redefine which class to instantiate?

  2. How can a class defer instantiation to subclasses?

For example, MazeGame provides the instantiation capability to subclass like MagicMazeGame.

enter image description here

where,

public abstract class MazeGame {
    private final List<Room> rooms = new ArrayList<>();

    public MazeGame() {
        Room room1 = makeRoom();
        Room room2 = makeRoom();
        room1.connect(room2);
        rooms.add(room1);
        rooms.add(room2);
    }

    abstract protected Room makeRoom();
}

Read answer.

Of course, this is a creational pattern, so design should be around simplifying instantiation of a class.


My question is,

What is the advantage of factory method pattern, introducing MagicGame class that provides a template method(public MazeGame(){..}) and defer instantiation to subclass MagicMazeGame or OrdinaryMazeGame?

Is deferring instantiation to subclass for only abstracting the below intricacies in a class like MagicMazeGame,

        Room room1 = MagicMazeGame();
        Room room2 = MagicMazeGame();
        room1.connect(room2);
        rooms.add(room1);
        rooms.add(room2);

and provide a uniform creation logic in every class MagicMazeGame or class OrdinaryMazeGame, as shown below,

public class MagicMazeGame extends MazeGame {
    public MagicMazeGame() {
        super();
    } 
    @Override
    protected Room makeRoom() {
        return new MagicRoom(); 
    }
}

Upvotes: 3

Views: 1498

Answers (1)

Fabio Carpinato
Fabio Carpinato

Reputation: 1181

The advantage of using the factory method pattern is that you decouple the business logic of creation of a class from the actual logic of the class, because if you don't have that factory method, every class that you add on your system needs to have a factory method inside, and when you have to change something about the creation you may have to deal with all of that set of classes ( bad for the open-closed principle )

Upvotes: 4

Related Questions