FazBrowse Wikipedia Viewer | Main Page |
Search Wikipedia:
|
Viewing: https://en.wikipedia.org/wiki/Factory_method_pattern

Factory method pattern

Contents
        C#
        PHP
        Python
Uses
See also
Notes

In object-oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact classes. Rather than by calling a constructor, this is accomplished by invoking a factory method to create an object. Factory methods can be specified in an interface and implemented by subclasses or implemented in a base class and optionally overridden by subclasses. It is one of the 23 classic design patterns described in the book Design Patterns and is subcategorized as a creational pattern.

this=0x6e5e90printMINE this=0x6e62c0printYOURS

C#

edit
\n/// Implementation of Factory - Used to create objects.\n/// </summary>\npublic class PersonFactory\n{\n public IPerson GetPerson(PersonType type)\n {\n switch (type)\n {\n case PersonType.Rural:\n return new Villager();\n case PersonType.Urban:\n return new CityPerson();\n default:\n throw new NotSupportedException();\n }\n }\n}\n"}}'>// Empty vocabulary of actual object publicinterfaceIPerson { stringGetName(); } publicclassVillager:IPerson { publicstringGetName() { return"Village Person"; } } publicclassCityPerson:IPerson { publicstringGetName() { return"City Person"; } } publicenumPersonType { Rural, Urban } /// <summary> /// Implementation of Factory - Used to create objects. /// </summary> publicclassPersonFactory { publicIPersonGetPerson(PersonTypetype) { switch(type) { casePersonType.Rural: returnnewVillager(); casePersonType.Urban: returnnewCityPerson(); default: thrownewNotSupportedException(); } } }

The above code depicts the creation of an interface called IPerson and two implementations called Villager and CityPerson. Based on the type passed to the PersonFactory object, the original concrete object is returned as the interface IPerson.

A factory method is just an addition to the PersonFactory class. It creates the object of the class through interfaces but also allows the subclass to decide which class is instantiated.

class MagicMazeGameextendsMazeGame{ @Override protectedMagicRoommakeRoom(){ returnnewMagicRoom(); } } class OrdinaryMazeGameextendsMazeGame{ @Override protectedOrdinaryRoommakeRoom(){ returnnewOrdinaryRoom(); } } MazeGameordinaryGame=newOrdinaryMazeGame(); MazeGamemagicGame=newMagicMazeGame();

PHP

edit

This PHP example shows interface implementations instead of subclassing (however, the same can be achieved through subclassing). The factory method can also be defined as publicand called directly by the client code (in contrast to the previous Java example).

makeCar();\nprint $car->getType();\n"}}'>/* Factory and car interfaces */ interface CarFactory { public function makeCar(): Car; } interface Car { public function getType(): string; } /* Concrete implementations of the factory and car */ class SedanFactory implements CarFactory { public function makeCar(): Car { return new Sedan(); } } class Sedan implements Car { public function getType(): string { return 'Sedan'; } } /* Client */ $factory = new SedanFactory(); $car = $factory->makeCar(); print $car->getType();

Python

edit

This Python example employs the same as did the previous Java example.

None:\n self.rooms = []\n self._prepare_rooms()\n\n def _prepare_rooms(self) -> None:\n room1 = self.make_room()\n room2 = self.make_room()\n\n room1.connect(room2)\n self.rooms.append(room1)\n self.rooms.append(room2)\n\n def play(self) -> None:\n print(f\"Playing using {self.rooms[0]}\")\n\n @abstractmethod\n def make_room(self):\n raise NotImplementedError(\"You should implement this!\")\n\n\nclass MagicMazeGame(MazeGame):\n def make_room(self) -> \"MagicRoom\":\n return MagicRoom()\n\n\nclass OrdinaryMazeGame(MazeGame):\n def make_room(self) -> \"OrdinaryRoom\":\n return OrdinaryRoom()\n\n\nclass Room(ABC):\n def __init__(self) -> None:\n self.connected_rooms = []\n\n def connect(self, room: \"Room\") -> None:\n self.connected_rooms.append(room)\n\n\nclass MagicRoom(Room):\n def __str__(self) -> str:\n return \"Magic room\"\n\n\nclass OrdinaryRoom(Room):\n def __str__(self) -> str:\n return \"Ordinary room\"\n\n\nordinaryGame = OrdinaryMazeGame()\nordinaryGame.play()\n\nmagicGame = MagicMazeGame()\nmagicGame.play()\n"}}'>fromabcimport ABC, abstractmethod classMazeGame(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) defplay(self) -> None: print(f"Playing using {self.rooms[0]}") @abstractmethod defmake_room(self): raise NotImplementedError("You should implement this!") classMagicMazeGame(MazeGame): defmake_room(self) -> "MagicRoom": return MagicRoom() classOrdinaryMazeGame(MazeGame): defmake_room(self) -> "OrdinaryRoom": return OrdinaryRoom() classRoom(ABC): def__init__(self) -> None: self.connected_rooms = [] defconnect(self, room: "Room") -> None: self.connected_rooms.append(room) classMagicRoom(Room): def__str__(self) -> str: return "Magic room" classOrdinaryRoom(Room): def__str__(self) -> str: return "Ordinary room" ordinaryGame = OrdinaryMazeGame() ordinaryGame.play() magicGame = MagicMazeGame() magicGame.play()

Uses

edit

See also

edit

Notes

edit
Cox, Brad J. (1986). Object-oriented programming: an evolutionary approach. Addison-Wesley. ISBN 978-0-201-10393-9.

  • View original on Wikipedia | Back | FazBrowse Home