php中设计模式有哪些
原创PHP中的设计模式概述
设计模式是解决软件设计中常见问题的经验性方法。在PHP开发中,合理运用设计模式可以增长代码的可维护性、可扩展性和可读性。以下是PHP中常见的设计模式简介。
1. 单例模式
单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供一个访问它的全局访问点。
<?php
class Singleton
{
private static $instance;
private function __construct()
{
}
public static function getInstance()
{
if (null === self::$instance) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
?>
2. 工厂模式
工厂模式是一种创建型设计模式,用于创建对象,而不必指定创建对象的类。工厂方法允许类将实例化的责任委托给子类。
<?php
interface Factory
{
public function create($type);
}
class ConcreteFactory implements Factory
{
public function create($type)
{
switch ($type) {
case 'ProductA':
return new ProductA();
break;
case 'ProductB':
return new ProductB();
break;
default:
throw new InvalidArgumentException('Invalid product type');
}
}
}
class ProductA
{
}
class ProductB
{
}
?>
3. 策略模式
策略模式是一种行为型设计模式,定义一系列算法,将每个算法封装起来,并使它们可以互换。
<?php
interface Strategy
{
public function execute();
}
class ConcreteStrategyA implements Strategy
{
public function execute()
{
echo "Strategy A is used to solve the problem.";
}
}
class ConcreteStrategyB implements Strategy
{
public function execute()
{
echo "Strategy B is used to solve the problem.";
}
}
class Context
{
private $strategy;
public function __construct(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function setStrategy(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function executeStrategy()
{
$this->strategy->execute();
}
}
?>
4. 观察者模式
观察者模式是一种行为型设计模式,当一个对象的状态出现改变时,自动通知所有依靠它的对象。
<?php
interface Observer
{
public function update($event);
}
interface Subject
{
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}
class ConcreteSubject implements Subject
{
private $observers;
public function __construct()
{
$this->observers = [];
}
public function attach(Observer $observer)
{
$this->observers[] = $observer;
}
public function detach(Observer $observer)
{
$index = array_search($observer, $this->observers);
if ($index !== false) {
unset($this->observers[$index]);
}
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update('Subject state changed');
}
}
}
class ConcreteObserver implements Observer
{
public function update($event)
{
echo "Observer received: " . $event;
}
}
?>
5. 适配器模式
适配器模式是一种结构型设计模式,允许不兼容接口的类一起工作。
<?php
interface Target
{
public function request();
}
class Adaptee
{
public function specificRequest()
{
return '.eetpadA eht fo roivaheb laicepS';
}
}
class Adapter implements Target
{
private $adaptee;
public function __construct(Adaptee $adaptee)
{
$this->adaptee = $adaptee;
}
public function request()
{
return strrev($this->adaptee->specificRequest());
}
}
?>
以上只是PHP中常见的设计模式的一部分,还有许多其他设计模式,如装饰器模式、代理模式、命令模式等。在实际开发中,通过需求选择合适的设计模式,可以大大节约代码质量和可维护性。