设计模式是可重复使用的软件设计解决方案,用于解决常见问题,提高代码可维护性、可扩展性和可重用性。php 中常见的设计模式包括:单例模式:确保一个类只创建一次实例。工厂模式:根据输入创建对象实例。策略模式:将算法封装到不同的类中,允许动态切换算法。
PHP 设计模式的深入理解
设计模式是可重复使用的解决方案,可以应用于常见的软件设计问题。在 PHP 中,使用设计模式可以提高代码可维护性、可扩展性和可重用性。
单例模式
描述:限制一个类的实例化次数为一次。
实现:
class Singleton
{
private static $instance;
private function __construct() {}
public static function getInstance(): Singleton
{
if (!self::$instance) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
实战案例:配置管理类,需要确保在整个应用程序中始终只有一个实例。
工厂模式
描述:根据输入创建对象的实例。
实现:
interface Shape
{
public function draw();
}
class Circle implements Shape
{
public function draw() { echo "Drawing circle"; }
}
class Square implements Shape
{
public function draw() { echo "Drawing square"; }
}
class ShapeFactory
{
public static function createShape(string $type): Shape
{
switch ($type) {
case 'circle':
return new Circle();
case 'square':
return new Square();
default:
throw new Exception("Invalid shape type");
}
}
}
实战案例:动态创建不同的数据库连接,取决于配置。
策略模式
描述:将算法封装到不同的类中,允许动态切换算法。
实现:
interface SortStrategy
{
public function sort(array $data): array;
}
class BubbleSort implements SortStrategy
{
public function sort(array $data): array
{
// Implement bubble sort algorithm
}
}
class QuickSort implements SortStrategy
{
public function sort(array $data): array
{
// Implement quick sort algorithm
}
}
class Sorter
{
private $strategy;
public function __construct(SortStrategy $strategy)
{
$this->strategy = $strategy;
}
public function sort(array $data): array
{
return $this->strategy->sort($data);
}
}
实战案例:对数据集进行不同的排序,取决于用户的选择。