目的
「リファクタリング」を理解するためにサンプルコードを PHP で書き換えてみました。
今回は「委譲の隠蔽」について書きます。
「委譲の隠蔽」 について
クライアントがあるオブジェクトの委譲クラスをコールしている。
カプセル化は、唯一とは言わないまでも、オブジェクト指向技術の鍵です。
例
変更前
<?php
class Person
{
private $_department;
private $_name;
public function __construct($arg)
{
$this->_name = $arg;
}
public function getName()
{
return $this->_name;
}
public function getDepartment()
{
return $this->_department;
}
public function setDepartment(Department $arg)
{
$this->_department = $arg;
}
}
class Department
{
private $_chargeCode;
/* @var Person */
private $_manager;
public function __construct(Person $manager)
{
$this->_manager = $manager;
}
public function getManager()
{
return $this->_manager;
}
}
$john = new Person('john');
$manager_aaa = new Person('manager_aaa');
$department = new Department($manager_aaa);
$john->setDepartment($department);
$manager = $john->getDepartment()->getManager();
echo $manager->getName() . "\n";
変更後
<?php
class Person2
{
private $_department;
private $_name;
public function __construct($arg)
{
$this->_name = $arg;
}
public function getName()
{
return $this->_name;
}
public function setDepartment(Department2 $arg)
{
$this->_department = $arg;
}
public function getManager()
{
return $this->_department->getManager();
}
}
class Department2
{
private $_chargeCode;
/* @var Person */
private $_manager;
public function __construct(Person2 $manager)
{
$this->_manager = $manager;
}
public function getManager()
{
return $this->_manager;
}
}
$john = new Person2('john');
$manager_aaa = new Person2('manager_aaa');
$department = new Department2($manager_aaa);
$john->setDepartment($department);
$manager = $john->getManager();
echo $manager->getName() . "\n";