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();
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值