Home > Article > Backend Development > strategy php design pattern Strategy strategy pattern
Copy the 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 caching
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< ;br/>";
// TTServer cache constructor
}
public function get($key)
{
// TTServer cache get method implementation
}
public function set($key,$value)
{
// Implementation of the set method of TTServer cache
}
public function del($key)
{
// Implementation of the del method of TTServer cache
}
}
// -- The following is a strategy for using without caching---- --
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
? >
The above introduces the strategy php design pattern Strategy strategy pattern, including the content of strategy. I hope it will be helpful to friends who are interested in PHP tutorials.