一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php设计模式的策略,适配器和观察者模式介绍

时间:2022-10-18 编辑:坚强 来源:一聚教程网

本文为小伙伴们带来了关于php设计模式的策略,适配器和观察者模式介绍的相关内容,感兴趣的小伙伴一起来看看吧。

策略模式

特点

定义一系列算法封装起来, 让他们可以相互替代,策略模式提供了管理相关算法族的办法, 提供了可以体会继承关系的棒法, 避免使用多重条件转移语句

实现

_stratege = $stratege;
    }
    public function goSchool()
    {
        $this->_stratege->goSchool();
    }
}
$traget = new Run();
$obj = new GoSchoolContext($traget);
$obj->goSchool();

适配器模式

特点

需要的东西在面前,但却不能用,而短时间又无法改造它,于是就想办法适配

实现

// 适配器
interface Charget
{
    public function putCharget();
}
class China implements Charget
{
    private $v = 220;
    public function putCharget()
    {
        return $this->v;
    }
}
class Adper extends China
{
    public function putCharget() {
        return parent::putCharget() / 2 + 10;
    }
}
class Phone
{
    public function charge(Charget $charge)
    {
        if ($charge->putCharget() != "120") {
            echo "不能充电";
        } else {
            echo "能充电";
        }
    }
}
$china = new China();
$adper = new Adper();
$phone = new Phone();
$phone->charge($adper);

观察者模式

特点

当一个对象状态发生变化时, 依赖他的对象全部收到通知, 并主动更新。观察者模式实现了低耦合, 非侵入式的通知与更新机制。

实现

_observers[] = $observer;
    }
    public function notify()
    {
        foreach($this->_observers as $object) {
            $object->watch();
        }
    }
}
// 观察者
class Cat1 implements Observer{
    public function watch(){
        echo "Cat1 watches TV
"; } } class Dog1 implements Observer{ public function watch(){ echo "Dog1 watches TV
"; } } class People implements Observer{ public function watch(){ echo "People watches TV
"; } } $action = new WatchAction(); $action->register(new Cat1()); $action->register(new People()); $action->register(new Dog1()); $action->notify();

总结

 以上就是关于php设计模式的策略,适配器和观察者模式介绍的全部内容了,感兴趣的小伙伴记得点击关注哦。

热门栏目