将调用者和实际实现者分开,减少耦合,通过中间类来关联两者
类图如下:
java实现
逻辑抽象类
public abstract class AbsReceiver {
public abstract void doSomething();
}
逻辑实现类
public class RealReceiver1 extends AbsReceiver {
@Override
public void doSomething() {
}
}
public class RealReceiver2 extends AbsReceiver {
@Override
public void doSomething() {
}
}
命令抽象类
public abstract class AbsCommand {
protected AbsReceiver receiver;
public AbsCommand(AbsReceiver receiver){
this.receiver = receiver;
}
public abstract void exe();
}
命令实现类
public class RealCommand1 extends AbsCommand {
public RealCommand1() {
super(new RealReceiver1());
}
@Override
public void exe() {
receiver.doSomething();
}
}
ublic class RealCommand2 extends AbsCommand {
public RealCommand2(){
super(new RealReceiver2());
}
@Override
public void exe() {
}
}
中转调度类
public class Invoke {
private AbsCommand command;
public void setCommand(AbsCommand command){
this.command = command;
}
public void action(){
command.exe();
}
}
php实现
abstract class AbsReceiver
{
public abstract function doSomething();
}
class RealReceiver1 extends AbsReceiver
{
public function doSomething()
{
echo 'RealReceiver1';
}
}
class RealReceiver2 extends AbsReceiver
{
public function doSomething()
{
echo 'RealReceiver2';
}
}
abstract class Command
{
protected $receiver;
public function __construct(AbsReceiver $receiver)
{
$this->receiver = $receiver;
}
public abstract function exe();
}
class RealCommand1 extends Command
{
public function __construct()
{
parent::__construct(new RealReceiver1);
}
public function exe()
{
$this->receiver->doSomething();
}
}
class RealComand2 extends Command
{
public function __construct()
{
parent::__construct(new RealReceiver2);
}
public function exe()
{
$this->receiver->doSomething();
}
}
class Invoke
{
private $command;
public function __set($name,$value)
{
if('command' == $name)
{
$this->command = $value;
}
}
public function __get($name)
{
if('command' == $name)
{
return $this->command;
}
}
public function action()
{
$this->command->exe();
}
}
$realCommand = new RealCommand1;
$invoke = new Invoke;
$invoke->command = $realCommand;
$invoke->action();