策略模式

2019-01-28  本文已影响20人  云龙789

首先要理解什么是策略。我个人理解这个词可以理解为解决方案。也就是你解决一个问题有多种解决方案的时候,可以选择策略模式,比如返回数据的格式,可以是 json 格式,可以是 array 格式的场景。
生活中,我觉得策略大家比较好理解的一个场景就是看房的时候,
一般的销售经理只会给你看一栋楼房,说其他的都已经卖完了,这其实就是一种策略。
那么我们按照这种场景来写一个 demo

<?php

/**
 *  看房接口
 * Interface Building
 */
interface Building
{
    public function show();
}

/**
 * 策略1 给看护看所有楼房
 * Class ShowAll
 */
class ShowAll implements Building
{
    public function show()
    {
        return 'you can see all house';
    }
}


/**
 * 策略2 给客户只看一栋楼
 * Class ShowOne
 */
class ShowOne implements Building
{
    public function show()
    {
        return 'you can only see one building house';
    }
}

/**
 * 工作中使用的类
 * Class HowShow
 */
class HowShow
{
    /**
     * @var Building  // 此处直接追踪抽象类即可,如果你想追踪 ShowAll|ShowOne 当然也是可以的
     */
    private $showType;

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

    public function show()
    {
        return $this->showType->show();
    }
}
//  使用
$see = new HowShow(new ShowOne());
echo $see->show();

上一篇下一篇

猜你喜欢

热点阅读