From wiki,
The Factory Method design pattern solves problems like:
-
How can an object be created so that subclasses can redefine which class to instantiate?
-
How can a class defer instantiation to subclasses?
For example, MazeGame
provides the instantiation capability to subclass like MagicMazeGame
.
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 solution should be around simplifying instantiation.
My question is,
What is the advantage of factory method pattern, that recommends a template method(public MazeGame(){..}
) and defer instantiation to subclass MagicMazeGame
or OrdinaryMazeGame
?
Is it to abstract the intricacies of constructor details? in every class like MagicMazeGame
or OrdinaryMazeGame
Aucun commentaire:
Enregistrer un commentaire