What Is the State Pattern? Explanation and PHP Implementation Example
The article introduces the State design pattern as a behavioral pattern that lets objects change their behavior when their internal state changes, compares it with the Strategy pattern, and provides a detailed PHP example illustrating its components and usage.
The State pattern is a behavioral design pattern that enables an object to automatically adjust its behavior when its internal state changes, allowing more flexible and maintainable code structures by mapping each state to a specific set of actions.
While similar to the Strategy pattern in promoting reusability and flexibility, the State pattern focuses on how an object's behavior varies with its state, whereas Strategy concentrates on interchangeable algorithms selected at runtime.
The article then presents a concrete PHP example of the State pattern, describing its three main components: the Context (which holds the current state and triggers state transitions), the State interface (defining the contract for concrete states), and Concrete State classes (each representing a distinct state with its own behavior).
Below is the full PHP implementation demonstrating these components and how the context transitions through Pending, Deploying, and Deployed states during successive calls to the deploy method.
<?php
// State接口
interface DeploymentState
{
public function handle(DeploymentManager $manager);
}
// 具体状态类
class PendingState implements DeploymentState
{
public function handle(DeploymentManager $manager)
{
echo "Deployment is pending.\n";
// Transition to next state
$manager->setState(new DeployingState());
}
}
// 具体状态类
class DeployingState implements DeploymentState
{
public function handle(DeploymentManager $manager)
{
echo "Deploying...\n";
sleep(5);
$manager->setState(new DeployedState());
}
}
// 具体状态类
class DeployedState implements DeploymentState
{
public function handle(DeploymentManager $manager)
{
echo "Deployment is successful.\n";
}
}
// 上下文类
class DeploymentManager
{
private $state;
public function __construct()
{
$this->setState(new PendingState());
}
public function setState(DeploymentState $state)
{
$this->state = $state;
}
public function deploy()
{
$this->state->handle($this);
}
}
// 示例
$manager = new DeploymentManager();
$manager->deploy(); // Output: Deployment is pending.
$manager->deploy(); // Output: Deploying...
$manager->deploy(); // Output: Deployment is successful.By reviewing this example, readers can see how the State pattern is concretely applied in PHP, gaining deeper insight into its practical use for managing object behavior across different states.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.