当前位置:主页 > 软件编程 > PHP代码 >

PHP设计模式的策略,适配器和观察者模式详解

时间:2022-06-26 10:33:37 | 栏目:PHP代码 | 点击:

策略模式

特点

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

实现

<?php
abstract class Strategy
{
    abstract function goSchool();
}
class Run extends Strategy
{
    public function goSchool() {
        echo "走路去学校";
    }
}
class Subway extends Strategy
{
    public function goSchool() {
        echo "地铁去学校";
    }
}
class Bike extends Strategy
{
    public function goSchool() {
        echo "公交去学校";
    }
}
class GoSchoolContext
{
    protected $_stratege;
    public function __construct($stratege) {
        $this->_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);

观察者模式

特点

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

实现

<?php
// 主题接口
interface Subject
{
    public function register(Observer $observer);
}
// 观察者接口
interface Observer
{
    public function watch();
}
// 主题
class WatchAction implements Subject
{
    public $_observers = [];
    public function register(\Observer $observer) {
        $this->_observers[] = $observer;
    }
    public function notify()
    {
        foreach($this->_observers as $object) {
            $object->watch();
        }
    }
}
// 观察者
class Cat1 implements Observer{
    public function watch(){
        echo "Cat1 watches TV<hr/>";
    }
}
class Dog1 implements Observer{
    public function watch(){
        echo "Dog1 watches TV<hr/>";
    }
}
 class People implements Observer{
    public function watch(){
        echo "People watches TV<hr/>";
    }
 }
$action = new WatchAction();
$action->register(new Cat1());
$action->register(new People());
$action->register(new Dog1());
$action->notify();

总结

 

您可能感兴趣的文章:

相关文章