php设计模式实现
单例模式(Singleton)
单例模式确保一个类只有一个实例,并提供一个全局访问点。适用于数据库连接、日志记录等场景。
class Singleton {
private static $instance;
private function __construct() {
// 私有化构造方法防止外部实例化
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone() {
// 防止克隆
}
}
// 使用
$instance = Singleton::getInstance();
工厂模式(Factory)
工厂模式通过一个共同的接口来创建对象,而不需要指定具体类。适用于对象创建逻辑复杂的场景。
interface Product {
public function getName();
}
class ConcreteProductA implements Product {
public function getName() {
return "Product A";
}
}
class ConcreteProductB implements Product {
public function getName() {
return "Product B";
}
}
class Factory {
public static function createProduct($type) {
switch ($type) {
case 'A':
return new ConcreteProductA();
case 'B':
return new ConcreteProductB();
default:
throw new Exception("Invalid product type");
}
}
}
// 使用
$product = Factory::createProduct('A');
echo $product->getName(); // 输出 "Product A"
观察者模式(Observer)
观察者模式定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会得到通知。
interface Observer {
public function update($data);
}
class ConcreteObserver implements Observer {
public function update($data) {
echo "Received update with data: " . $data . "\n";
}
}
class Subject {
private $observers = [];
public function attach(Observer $observer) {
$this->observers[] = $observer;
}
public function notify($data) {
foreach ($this->observers as $observer) {
$observer->update($data);
}
}
}
// 使用
$subject = new Subject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->notify("Some data");
策略模式(Strategy)
策略模式定义一系列算法,将每个算法封装起来并使它们可以互换。适用于需要动态切换算法的场景。
interface Strategy {
public function execute($a, $b);
}
class AddStrategy implements Strategy {
public function execute($a, $b) {
return $a + $b;
}
}
class SubtractStrategy implements Strategy {
public function execute($a, $b) {
return $a - $b;
}
}
class Context {
private $strategy;
public function __construct(Strategy $strategy) {
$this->strategy = $strategy;
}
public function executeStrategy($a, $b) {
return $this->strategy->execute($a, $b);
}
}
// 使用
$context = new Context(new AddStrategy());
echo $context->executeStrategy(5, 3); // 输出 8
适配器模式(Adapter)
适配器模式将一个类的接口转换成客户希望的另一个接口,使原本不兼容的类可以一起工作。
interface Target {
public function request();
}
class Adaptee {
public function specificRequest() {
return "Specific request";
}
}
class Adapter implements Target {
private $adaptee;
public function __construct(Adaptee $adaptee) {
$this->adaptee = $adaptee;
}
public function request() {
return $this->adaptee->specificRequest();
}
}
// 使用
$adaptee = new Adaptee();
$adapter = new Adapter($adaptee);
echo $adapter->request(); // 输出 "Specific request"
装饰器模式(Decorator)
装饰器模式动态地给对象添加额外的职责,提供比继承更灵活的扩展方式。
interface Component {
public function operation();
}
class ConcreteComponent implements Component {
public function operation() {
return "ConcreteComponent";
}
}
abstract class Decorator implements Component {
protected $component;
public function __construct(Component $component) {
$this->component = $component;
}
public function operation() {
return $this->component->operation();
}
}
class ConcreteDecoratorA extends Decorator {
public function operation() {
return "DecoratorA(" . parent::operation() . ")";
}
}
class ConcreteDecoratorB extends Decorator {
public function operation() {
return "DecoratorB(" . parent::operation() . ")";
}
}
// 使用
$component = new ConcreteComponent();
$decoratorA = new ConcreteDecoratorA($component);
$decoratorB = new ConcreteDecoratorB($decoratorA);
echo $decoratorB->operation(); // 输出 "DecoratorB(DecoratorA(ConcreteComponent))"
责任链模式(Chain of Responsibility)
责任链模式使多个对象都有机会处理请求,从而避免请求发送者和接收者之间的耦合。
abstract class Handler {
protected $successor;
public function setSuccessor(Handler $successor) {
$this->successor = $successor;
}
abstract public function handleRequest($request);
}
class ConcreteHandlerA extends Handler {
public function handleRequest($request) {
if ($request === 'A') {
return "Handled by A";
} elseif ($this->successor !== null) {
return $this->successor->handleRequest($request);
}
return null;
}
}
class ConcreteHandlerB extends Handler {
public function handleRequest($request) {
if ($request === 'B') {
return "Handled by B";
} elseif ($this->successor !== null) {
return $this->successor->handleRequest($request);
}
return null;
}
}
// 使用
$handlerA = new ConcreteHandlerA();
$handlerB = new ConcreteHandlerB();
$handlerA->setSuccessor($handlerB);
echo $handlerA->handleRequest('B'); // 输出 "Handled by B"






