Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
Niidae Wiki
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Factory method pattern
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
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>
Summary:
Please note that all contributions to Niidae Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Encyclopedia:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
Factory method pattern
(section)
Add topic