php設計模式之命令鏈模式

1. 使用場景

1. 命令連模式可以使用在用戶登陸註冊的時候處理不同角色用戶的業務邏輯,與變量值 

2. 代碼實例

<?php
/**
 * command interface
 *
*/
interface MyCommand
{
    public function onCommand( $name, $args );
}

//user register
class Register
{
    private $_commandsChain = array();

    public function addCommand( $cmd )
    {
        $this->_commandsChain []= $cmd;
    }

    public function runCommand( $name, $args )
    {
        foreach( $this->_commandsChain as $cmd )
        {
            if ($cmd->onCommand( $name, $args )) {
                return;
            }
        }
    }
}

//common logic
class CommonCommand implements MyCommand
{
    public function onCommand( $name, $args )
    {
        if ($name != 'common_user' ) {
            return false;
        }
        echo "I am common member\n";
        return true;
    }
}

//vip logic
class VipCommand implements MyCommand
{
    public function onCommand( $name, $args )
    {
        if ($name != 'vip_user') {
            return false;
        }
        echo "I am vip member\n";
        return true;
    }
}

//實例化註冊器
$cc = new Register();
//運行普通用戶的處理邏輯
$cc->addCommand( new CommonCommand() );
//運行高級用戶的處理邏輯
$cc->addCommand( new VipCommand() );
//運行普通用戶的處理邏輯
$cc->runCommand( 'common_user', null );
//運行高級用戶的處理邏輯
$cc->runCommand( 'vip_user', null );

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章