重用性是面向对象设计的主要目标之一,而紧耦合便是它的敌人。当我们看到系统中一个组件的改变迫使系统其他许多地方也发生改变的时候,就可以诊断为紧耦合了。
简单实现代码:
class RegistrationMgr
{
public function register(Lesson $lesson){
//处理该课程
//通知某人
$notifier = Notifier::getNotifier();
$notifier->inform("new lesson: cost ({$lesson->cost()})");
}
}
abstract class Notifier
{
static function getNotifier()
{
//根据配置或其他逻辑获得具体的类
if(rand(1,2) == 1){
return new MailNotifier();
}else{
return new TextNotifier();
}
}
abstract function inform($message);
}
class MailNotifier extends Notifier
{
public function inform($message)
{
print "MAIL notification : {$message} \n";
}
}
class TextNotifier extends Notifier
{
public function inform($message)
{
print "TEXT notification : {$message} \n";
}
}
$lessons1 = new Seminar(4, new TimedCostStrategy());
$lessons2 = new Lecture(4, new FixedCostStrategy());
$mgr = new RegistrationMgr();
$mgr->register($lessons1);
$mgr->register($lessons2);
代码解耦的方式暗含 策略设计模式