strategy php design pattern Strategy strategy pattern

WBOY
Release: 2016-07-29 08:45:45
Original
839 people have browsed it

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.

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!