I know there are a lot of questions out there about differences of different factory patterns, but the answers are so different and confusing. The books that i read use uncl
First of all , I don't see the "factory method pattern" as a standalone pattern (never headred of this pattern untill i've read wikipedia as you said in your question) . I see it more as a mix of factory pattern + strategy pattern .
You can imagine an object factory as a simple object creator .
When strategy pattern comes into play inside an object factory then you begin to add more logic about the creation of the object, to hide it from the client (the client should not know how the objects are created, leave this responsability to the factory).
A factory can be of many types (the decision of factory creation depends on many factors) :
- When thinking about object associations , an object may be composed by multiple objects . Here the root object may have a factory method that will create the need objects . This factory method is responsible for checking if the newly added objects keep the root in a valid state . So here the strategy pattern (factory method pattern as you call it) may come into play :
class Car {
public $carType;
public $audioSystem;
public function __construct($carType) {
$this->carType = $carType;
$this->audioSystemFactory();
}
public function audioSystemFactory() {
if ($this->carType == 'hipster') {
$this->audioSystem = new VynilPlayer();
}
else {
$this->audioSystem = new Mp3Player();
}
}
public function startMusic($albumName) {
$this->audioSystem->playSongs($albumName);
}
}
class VynilPlayer {
public $vynilAlbums = array('MJ TOP HITS', 'JUSTIN BIEBER TOP HITS');
public function playSongs($albumName) {
$this->loadVynil();
$this->startPlayer();
}
public function loadVynil() {
}
public function startPlayer() {
}
}
class Mp3Player {
public $dvdAlbums = array('MJ TOP HITS', 'JUSTIN BIEBER TOP HITS');
public function playSongs($albumName) {
$this->loadDVD();
$this->startPlayer();
}
public function loadDVD() {
}
public function startPlayer() {
}
}
You can also have a factory class that is responsible for the creation of only one type of object . You make a factory class per object type when the creation logic is very complex .
Even a primitive form of instanciation like a class constructor can be viewed as an object factory .
Factories are made to hide the implementation logic of some objects . You add strategy pattern to a factory to hide these details from the client .