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

<?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");
本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/7453138.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)