Home > Backend Development > PHP Tutorial > PHP design pattern Strategy (strategy pattern)_PHP tutorial

PHP design pattern Strategy (strategy pattern)_PHP tutorial

WBOY
Release: 2016-07-21 15:27:12
Original
814 people have browsed it

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
?>

www.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...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template