码迷,mamicode.com
首页 > 其他好文 > 详细

命令模式

时间:2015-06-30 23:20:20      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

命令模式用一句话表示就是说:一个命令一个类。在面向对象程式设计的范畴中,命令模式是一种设计模式, 将一个请求封装为一个对象, 从而使你可用不同的请求对客户进行参
数。

技术分享

class Factory {
	
	static public function getCommand($_action) {
		$_className = $_action;	
		$_classFile = $_action.‘.class.php‘;
		require $_classFile;
		return new $_className();
	}
}

class Controller {
	private $_context;
	
	public function __construct() {
		$this->_context = new Context();
	}
	
	public function getContext() {
		return $this->_context;
	}
	
	public function process() {
		$_cmd = Factory::getCommand($this->_context->getParam(‘action‘));
		if ($_cmd->execute($this->_context)) {
			return $this->_context->getSucc();
		} else {
			return $this->_context->getError();
		}
	}
}

class Context {
	private $_params = array();
	private $_succ;
	private $_error;
	
	public function addParam($_key, $_value) {
		$this->_params[$_key] = $_value;
	}
	
	public function getParam($_key) {
		return $this->_params[$_key];
	}
	
	public function setSucc($_info) {
		$this->_succ = $_info;
	}
	
	public function setError($_info) {
		$this->_error = $_info;
	}
	
	public function getSucc() {
		return $this->_succ;
	}
	
	public function getError() {
		return $this->_error;
	}
	
	
}

class Login {
	private $_user = ‘admin‘;
	private $_pass = ‘123456‘;
	
	public function execute(Context $_context) {
		if ($this->_user == $_context->getParam(‘user‘) && $this->_pass == $_context->getParam(‘pass‘)) {
			return true;
		}
		return false;
	}
}

class FeedBack {
	
	public function execute(Context $_context) {
		if ($_context->getParam(‘name‘) && $_context->getParam(‘date‘) && $_context->getParam(‘info‘)) {
			return true;
		}
		return false;
	}
}

$_c = new Controller();
$_context = $_c->getContext();
$_context->addParam(‘action‘, ‘Login‘);
$_context->addParam(‘user‘, ‘admin‘);
$_context->addParam(‘pass‘, ‘123456‘);
$_context->setSucc(‘登录成功!‘);
$_context->setError(‘登录失败!‘);
echo $_c->process();

$_context->addParam(‘action‘, ‘FeedBack‘);
$_context->addParam(‘name‘, ‘dddd‘);
$_context->addParam(‘date‘, ‘kkkk‘);
$_context->addParam(‘info‘, ‘eeee‘);
$_context->setSucc(‘反馈成功!‘);
$_context->setError(‘反馈失败!‘);
echo $_c->process();

命令模式的三个组成部分别为:
1.实例化命令对象类:Factory.class.php (其实就是一个简单工厂)
2.部署命令对象的调用者类:Controller.class.php (一个控制器,MVC 会涉及到)
3.接收命令的接受者类:Context.class.php (一个模型,Model)

命令模式

标签:

原文地址:http://www.cnblogs.com/jsmiao/p/4611699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!