PHP Design pattern Strategy (strategy mode) _php skills

Source: Internet
Author: User
Copy Code code as follows:

<?php
/**
* Policy mode (strategy.php)
*
* Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other, and the change in the algorithm can be independent of the client using it
*
*/

---The following is a closed----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<br/>";
}

Public function Get ($key)
{
return false;
}

Public function set ($key, $value)
{
return true;
}

Public Function del ($key)
{
return false;
}
}

File caching
Class Filecache implements Cachetable
{
Public Function __construct ()
{
echo "Use filecache<br/>";
File Cache Constructor
}

Public function Get ($key)
{
Implementation of the Get method for file caching
}

Public function set ($key, $value)
{
Set method implementation of file caching
}

Public Function del ($key)
{
Implementation of File Cache Del method
}
}

Ttserver
Class Ttcache implements Cachetable
{
Public Function __construct ()
{
echo "Use ttcache<br/>";
Ttserver Cache Constructor
}

Public function Get ($key)
{
Ttserver Cache's Get method implementation
}

Public function set ($key, $value)
{
Implementation of Set method for Ttserver caching
}

Public Function del ($key)
{
Implementation of Ttserver Cache Del method
}
}

--The following are policies that use no 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 ();
}
}

--an example---
$mdlUser = new Usermodel ();
$mdlProduct = new Porductmodel ();
$mdlProduct->setcache (New Filecache ()); changing caching policies
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.