The strategic pattern of design pattern

1. Policy mode: it is the behavior mode of the object, which is intended to encapsulate a group of algorithms. Dynamic selection of the required algorithm and use.

Implementation steps:

1. Define abstract classes (define common abstract methods that all subclasses must implement)

2. Define specific policy classes (common methods to implement parent classes)

3. Define the environment role class (privatization states Abstract role variables, overloading construction methods, executing abstract methods)

Objective: to realize different channel interfaces according to different channels;

For example, the following implementation of payment channel related interfaces;

Channel.php

<?php
/*Policy mode:
Intention: define a series of algorithms, encapsulate them one by one, and make them interchangeable.
*/
//Channel class abstract class
abstract class Channel
{
    abstract function getChannel(); //Get channel status and other attributes
    abstract function getChannelFee(); //Access channel rate
    abstract function getChannelConfig();//Obtain channel transaction secret key and other information
}

//Sub channel cmbc Class implementation
class cmbc extends Channel
{
    protected $name;
    protected $config;
    protected $fee;
    function __construct($name){
        $this->name = $name;
    }
    function getChannel(){
        return $this->name;
    }
    function getChannelFee(){
        return $this->fee;
    }
    function getChannelConfig(){
        return $this->config;
    }
}
//Sub channel alipay 
class alipay extends Channel
{
    protected $name;
    protected $config;
    protected $fee;
    function __construct($name){
        $this->name = $name;
    }
    function getChannel(){
        return $this->name;
    }
    function getChannelFee(){
        return $this->fee;
    }
    function getChannelConfig(){
        return $this->config;
    }
}
//Total routing
class RouterChannel
{
    public $chn;
    public function __construct($channel){
        $this->chn = $channel;
    }
}
$router = new RouterChannel(new cmbc('Livelihood'));
echo $router->chn->getChannel();
$router = new RouterChannel(new alipay('Alipay'));
echo $router->chn->getChannel();
?>

Tags: PHP

Posted on Mon, 04 Nov 2019 13:35:37 -0800 by kishore_marti