When to Use the Factory Method Pattern
In part, design patterns are selected based on what you want to be able to change. The table shows that the Factory Method should be used when the subclass of an object instantiated can vary.
Purpose | Scope | Name | What Can Vary |
---|---|---|---|
Creative | Class | Factory Method | Subclass of object instantiated |
Object | Prototype | Class of object instantiated | |
Structural | Class | Adapter* | Interface of object |
Object | Adapter* Decorator | Object responsibility without subclassing | |
Behavioral | Class | Template Method | Steps in algorithm |
Object | State | States of objects | |
Object | Strategy | An algorithm | |
Object | Chain of Responsibility | Object that can fulfill request | |
Object | Observer | Number of objects that depend on other objects; how many dependent objects can stay up to date |
Product.php
interface Product { public function getProperties(); }
GraphicProduct.php
include_once 'Product.php'; class GraphicProduct implements Product { private $mfgProduct; public function getProperties() { $this->mfgProduct = 'This is a graphic product'; return $this->mfgProduct; } }
TextProduct.php
include_once 'Product.php'; class TextProduct implements Product { private $mfgProduct; public function getProperties() { $this->mfgProduct = 'This is text'; return $this->mfgProduct; } }
Creator.php
abstract class Creator { protected abstract function factoryMethod(); public function startFactory() { $mfg = $this->factoryMethod(); return $mfg; } }
GraphicFactory.php
include_once 'Creator.php'; include_once 'GraphicProduct.php'; class GraphicFactory extends Creator { protected function factoryMethod() { $product = new GraphicProduct(); return $product->getProperties(); } }
TextFactory.php
include_once 'Creator.php'; include_once 'TextProduct.php'; class TextFactory extends Creator { protected function factoryMethod() { $product = new TextProduct(); return $product->getProperties(); } }
Client.php
include_once 'GraphicFactory.php'; include_once 'TextFactory.php'; class Client { private $someGraphic; private $someText; public function __construct() { $this->someGraphic = new GraphicFactory(); echo $this->someGraphic->startFactory(). ' '; $this->someText = new TextFactory(); echo $this->someGraphic->startFactory() .' '; } } $worker = new Client();
The Factory Method Pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass. The Factory Method helps to simplify demands made by growing and increasingly complex sites where new products are introduced.
Der Beitrag Factory Method Pattern erschien zuerst auf Jens Freudenau.