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!
==== [[Python (programming language)|Python]] ==== This Python example employs the same as did the previous Java example. <syntaxhighlight lang="python3"> from abc import ABC, abstractmethod class MazeGame(ABC): def __init__(self) -> None: self.rooms = [] self._prepare_rooms() def _prepare_rooms(self) -> None: room1 = self.make_room() room2 = self.make_room() room1.connect(room2) self.rooms.append(room1) self.rooms.append(room2) def play(self) -> None: print(f"Playing using {self.rooms[0]}") @abstractmethod def make_room(self): raise NotImplementedError("You should implement this!") class MagicMazeGame(MazeGame): def make_room(self) -> "MagicRoom": return MagicRoom() class OrdinaryMazeGame(MazeGame): def make_room(self) -> "OrdinaryRoom": return OrdinaryRoom() class Room(ABC): def __init__(self) -> None: self.connected_rooms = [] def connect(self, room: "Room") -> None: self.connected_rooms.append(room) class MagicRoom(Room): def __str__(self) -> str: return "Magic room" class OrdinaryRoom(Room): def __str__(self) -> str: return "Ordinary room" ordinaryGame = OrdinaryMazeGame() ordinaryGame.play() magicGame = MagicMazeGame() magicGame.play() </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)