Lazy initialization is the tactic of del…
Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:
- using a factory method to get instances of a class (factory method pattern)
- storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (compare with a singleton pattern)
- using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).
A Simple PHP Example
class User{
protected $_id;
public function getId(){
return $this->_id;
}
}
class Post{
protected $_userId;
protected $_text;
/**** @var User*/
protected $_user;
public function setUser(User $user){
$this->_userId = $user->getId();
$this->_user = $user;
}
public function getUser(){
if (!$this->_user) {
$this->_user = new User($this->_userId);
}
return $this->_user;
}
public function setText($text){
$this->_text = $text;
}
public function getText(){
return $this->_text;
}
}
A PHP 5 Example
class View{
protected $_values = array();
public function set($name, $value){
$this->_values[$name] = $value;
}
public function render($file){
extract($this->_values);
ob_start(); include($file);
return ob_get_clean();
}
}
class Page{
/*** View object.** @var View*/
protected $_view;
public function __construct(){
// remove attribute to use the __get magic method in first access
unset($this->_view);
}
public function __get($name){
if ($name == '_view') { // load view object
$this->_view = new View();
return $this->_view;
}
}
public function actionIndex(){
$this->_view->set('title', 'Lazy Initialization');
print $this->_view->render('lazy.tpl');
}
}
Recent Comments