Definition
"Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."
Example
หรือ
ref : wiki
"Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."
Example
public class MazeGame { public MazeGame() { Room room1 = makeRoom(); Room room2 = makeRoom(); room1.connect(room2); this.addRoom(room1); this.addRoom(room2); } protected Room makeRoom() { return new OrdinaryRoom(); } } public class MagicMazeGame extends MazeGame { @Override protected Room makeRoom() { return new MagicRoom(); } }
หรือ
/* factory and car interfaces */ interface CarFactory { public function makeCar(); } interface Car { public function getType(); } /* concrete implementations of the factory and car */ class SedanFactory implements CarFactory { public function makeCar() { return new Sedan(); } } class Sedan implements Car { public function getType() { return 'Sedan'; } } /* client */ $factory = new SedanFactory(); $car = $factory->makeCar(); print $car->getType();
ref : wiki
ความคิดเห็น