Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Factory method pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====[[Java (programming language)|Java]]==== This [[Java (programming language)|Java]] example is similar to one in the book ''[[Design Patterns]].'' [[File:Maze game UML.svg]] The <code>MazeGame</code> uses <code>Room</code> but delegates the responsibility of creating <code>Room</code> objects to its subclasses that create the concrete classes. The regular game mode could use this template method: <syntaxhighlight lang="java"> public abstract class Room { abstract void connect(Room room); } public class MagicRoom extends Room { public void connect(Room room) {} } public class OrdinaryRoom extends Room { public void connect(Room room) {} } 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(); } </syntaxhighlight> The <code>MazeGame</code> constructor is a [[Template method pattern|template method]] that adds some common logic. It refers to the <code>makeRoom()</code> factory method that encapsulates the creation of rooms such that other rooms can be used in a subclass. To implement the other game mode that has magic rooms, the <code>makeRoom</code> method may be overridden: <syntaxhighlight lang="java"> public class MagicMazeGame extends MazeGame { @Override protected MagicRoom makeRoom() { return new MagicRoom(); } } public class OrdinaryMazeGame extends MazeGame { @Override protected OrdinaryRoom makeRoom() { return new OrdinaryRoom(); } } MazeGame ordinaryGame = new OrdinaryMazeGame(); MazeGame magicGame = new MagicMazeGame(); </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)