Copy code The code is as follows:
/**
* Strategy pattern (Strategy.php)
*
* Define a series of algorithms, encapsulate them one by one, and make them interchangeable. The changes in the algorithm used can be independent of the customers who use it.
*
*/
// ---The following is the closure of a series of algorithms----
interface CacheTable
{
public function get($key);
public function set($key,$value);
public function del($key);
}
// Do not use cache
class NoCache implements CacheTable
{
public function __construct(){
echo "Use NoCache
";
}
public function get($key)
{
return false;
}
public function set ($key,$value)
{
return true;
}
public function del($key)
{
return false;
}
}
// File cache
class FileCache implements CacheTable
{
public function __construct()
{
echo "Use FileCache
";
// File cache constructor
}
public function get($key)
{
// File cache get method implementation
}
public function set($key,$value)
{
//File cache set method implementation
}
public function del($key)
{
/ / File cache del method implementation
}
}
// TTServer
class TTCache implements CacheTable
{
public function __construct()
{
echo "Use TTCache
";
// TTServer cache constructor
}
public function get($key)
{
// TTServer cache get Method implementation
}
public function set($key,$value)
{
// TTServer cached set method implementation
}
public function del ($key)
{
// TTServer cache del method implementation
}
}
// -- The following is a strategy for using no cache -------
class Model
{
private $_cache;
public function __construct()
{
$this->_cache = new NoCache();
}
public function setCache($cache)
{
$this->_cache = $cache;
}
}
class UserModel extends Model
{
}
class PorductModel extends Model
{
public function __construct()
{
$this->_cache = new TTCache();
}
}
// -- Example---
$mdlUser = new UserModel();
$mdlProduct = new PorductModel();
$mdlProduct->setCache(new FileCache()); // Change cache strategy
?>
http://www.bkjia.com/PHPjc/323797.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323797.htmlTechArticleCopy the code as follows: ?php /** * Strategy pattern (Strategy.php) * * Define a series of algorithms , encapsulate them one by one, and make them interchangeable, and the changes in the algorithm used can be independent...