策略设计模式

作者: wudanyang | 来源:发表于2018-03-01 20:17 被阅读17次

什么是策略设计模式

策略模式定义了一系列的算法,并且将每一个算法封装起来。这几个算法是可以相互替换的。策略模式让算法独立于使用它的客户而独立变化。

简单来讲:策略模式可以让你想用哪种方式实现就用哪种方式实现。例如:php 使用 pdo 或是 mysqli 来连接 mysql

为什么要使用

  1. 隐藏具体实现细节
  2. 方便切换算法

类型

行为型模式

参与者

  • Context 上下文类

    • 用于管理具体使用的策略
  • IStrategy 策略接口

  • ConcreteStrategy 具体策略类

    • 实现具体的算法

例子

<?php

/**
 * 策略接口
 *
 * Interface IStrategy
 */
interface IStrategy {
    public function algorithm();
}

class PhpStrategy implements IStrategy {
    public function algorithm()
    {
        echo "php algorithm: echo 'Hello, World'".PHP_EOL;
    }
}

class LuaStrategy implements IStrategy {
    public function algorithm()
    {
        echo "Lua algorithm: print('Hello, World')".PHP_EOL;
    }
}

class CppStrategy implements IStrategy {
    public function algorithm()
    {
        echo 'C++ algorithm: cout << "Hello, World" << endl;'.PHP_EOL;
    }
}

/**
 * 上下文类,用于管理使用的具体策略
 *
 * Class Context
 */
class Context {
    private $strategy;

    public function __construct(IStrategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function setLanguage(IStrategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function printHelloWorld()
    {
        $this->strategy->algorithm();
    }
}


/**
 * 客户端代码
 * Class Client
 */
class Client {
    public function run()
    {
        $context = new Context(new PhpStrategy());
        $context->printHelloWorld();

        $context->setLanguage(new CppStrategy());
        $context->printHelloWorld();

        $context->setLanguage(new LuaStrategy());
        $context->printHelloWorld();
    }
}

$client = new Client();
$client->run();
php algorithm: echo 'Hello, World'
C++ algorithm: cout << "Hello, World" << endl;
Lua algorithm: print('Hello, World')

相关文章

网友评论

    本文标题:策略设计模式

    本文链接:https://www.haomeiwen.com/subject/ptdnxftx.html