<?php
/**
* 某个对象不必自身包含逻辑,而是能够应用其他对象的算法
*
*/
class LogStrategy
{
public $message;
public $level;
public $type;
protected $_strategy;
public function __construct($message, $level, $type)
{
$this->message = $message;
$this->level = $level;
$this->type = $type;
}
public function setStrategy($strategyObj)
{
$this->_strategy = $strategyObj;
}
public function log()
{
$this->_strategy->log($this);
}
}
interface Log
{
public function log($logObject);
}
class DBStrategy implements Log
{
public function log($logObject)
{
$this->_logToDB($logObject);
}
private function _logToDB($logObject)
{
var_dump($logObject);
echo "log to db
";
}
}
class QUEStrategy implements Log
{
public function log($logObject)
{
$this->_logToQUE($logObject);
}
private function _logToQUE($logObject)
{
var_dump($logObject);
echo "log to queue";
}
}
echo "<pre>";
$log = new LogStrategy("can't find the file", "error", "user_error");
$log->setStrategy(new DBStrategy());
$log->log();
$log->setStrategy(new QUEStrategy());
$log->log();