12. Factory Pattern
●
Creates Objects without having to instantiate the classes
directly.
●
Factories creates Objects.
●
When...
●
Keep DRY when complex object creation
needs to be re-usable.
●
Encapsulate several Object creation in one.
13. Example : Factory
Class Factory {
public function create() {
return new Thing();
}
}
Class Thing {
public function doSomething() {
echo “Hello PHP'ers!”;
}
}
$factory = new Factory();
$thingObj =
$factory->create();
$thing->doSomething();
14. Singleton Pattern
●
Creates Objects without direct instantiation.
●
Does not allow more than one instance of self
●
Ensure only one instance of an obejct at any given time.
●
When...
●
Require only one instance of an class.
●
Need only one connection to a server.
15. Example : Singleton
Class SomeSingleton {
public static $instance;
private function __construct(){}
private function __clone(){}
public static function getInstance(){
If(!self::$instance instanceof self) {
self::$instance = new self();
}
Return self::$instance;
}
}
----------------------------------------------------------------------------------------
$someStaticInstance = SomeSingleton::getInstance();
$someInstance = new SomeSingleton();
16. Decorator Pattern
●
Decorator adds functionality to an object without changing
the Object's behavior.
●
When...
●
Add features or methods to an object, that are not
part of the Core logic.
●
Need extended functionality for specific use cases.
17. Example : Decorator
class User{
Public $firstName = '';
Public $lastName = '';
}
Class UserDecorator{
Private $user;
Public function __construct(User $user){
$this->user = $user;
}
Public function getFullName() {
Return “{$this->user->firstName} {$this->user->lastName}”;
}
}
18. Example : Decorator...
$user = new User();
$user->firstName = 'Chuck';
$user->firstName = 'Norris';
$decoratedUser = new UserDecorator($user);
echo $decoratedUser->getFullName();
// 'Chuck Norris'
19. Observer Pattern
●
Objects(Subject) register other objects (Observer) that
react to state changes of their subject.
●
In simple words, Observer looks for changes and
do something
l
When...
●
State Changes of an Object affect other objects or datasets
●
Event Handling
●
Data persistence
●
Logging