一天一个设计模式(18)——状态模式

本文介绍状态模式的概念及其在PHP中的具体实现。状态模式允许对象在其内部状态改变时改变其行为,如同该对象似乎修改了它的类。通过将状态封装在不同的类中并允许对象在这些状态之间切换,状态模式提供了一种灵活的方式来管理对象的状态变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

状态模式 

当状态改变时,类的行为也发生改变。

状态模式是以面向对象的方式实现状态机的行为设计模式。对于状态模式,通过将每个单独状态实现为派生类的状态模式接口, 来实现一个状态机,并通过调用模式超类的方法来实现状态转换。状态模式可以被解释为一种策略模式,它能够通过调用模式接口定义的方法来切换当前策略。

实例

<?php
interface WritingState{
    public function write(string $words);
}

class UpperState implements WritingState{
    public function write(string $words){
        echo strtoupper($words);
    }
}

class LowerState implements WritingState{
    public function write(string $words){
        echo strtolower($words);
    }
}

class DefaultState implements WritingState{
    public function write(string $words){
        echo $words;
    }
}

class Editor{
    private $state;
    public function __construct(WritingState $state){
        $this->state=$state;
    }

    public function setState($state){
        $this->state=$state;
    }

    public function type(string $words){
        $this->state->write($words);
    }
}

$state=new DefaultState();
$editor=new Editor($state);
$editor->type("First Type");

$editor->setState(new UpperState());
$editor->type("Second Type");

$editor->setState(new LowerState());
$editor->type("Third Type");
状态模式实例

 

转载于:https://www.cnblogs.com/Bin-x/p/7453138.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值