php 自函数编写常用设计模式:单例模式:确保类只实例化一次。工厂模式:基于共同接口创建不同对象。策略模式:将特定算法与调用代码分离。适配器模式:让一个类与使用另一个接口的类协同工作。

引言
自函数是 PHP 中一个强大的功能,它允许开发者创建自己的函数,极大地提高了编码的可扩展性和可重用性。本文将介绍几种常用的自函数编写设计模式,并提供其实战案例。
单例模式
立即学习“PHP免费学习笔记(深入)”;
用途:当需要确保类只被实例化一次时使用此模式。
代码示例:
class Singleton {
private static $instance = null;
private function __construct() {}
public static function getInstance(): Singleton {
if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}工厂模式
用途:当需要创建不同类型的对象但基于共同接口时使用此模式。
代码示例:
interface Shape {
public function draw();
}
class Rectangle implements Shape {
public function draw() {
echo "绘制矩形";
}
}
class Circle implements Shape {
public function draw() {
echo "绘制圆形";
}
}
class ShapeFactory {
public static function createShape($type): Shape {
switch ($type) {
case "Rectangle":
return new Rectangle();
case "Circle":
return new Circle();
default:
throw new Exception("不支持的形状类型");
}
}
}策略模式
用途:当需要将特定算法与调用代码分离时使用此模式。
代码示例:
interface Strategy {
public function execute();
}
class ConcreteStrategyA implements Strategy {
public function execute() {
echo "策略 A 执行";
}
}
class ConcreteStrategyB implements Strategy {
public function execute() {
echo "策略 B 执行";
}
}
class Context {
private $strategy;
public function __construct(Strategy $strategy) {
$this->strategy = $strategy;
}
public function executeStrategy() {
$this->strategy->execute();
}
}适配器模式
用途:当需要让一个类与使用另一个接口的类协同工作时使用此模式。
代码示例:
class LegacyClass {
public function oldMethod() {
echo "旧方法";
}
}
class Adapter implements TargetInterface {
private $legacyClass;
public function __construct(LegacyClass $legacyClass) {
$this->legacyClass = $legacyClass;
}
public function newMethod() {
$this->legacyClass->oldMethod();
}
}
interface TargetInterface {
public function newMethod();
}实战案例
一个简单的商品计算器应用程序:
use DesignPatterns\Factory;
$factory = new Factory();
$productA = $factory->createProduct("A");
$productB = $factory->createProduct("B");
$totalCost = $productA->getPrice() + $productB->getPrice();
echo "总成本:$totalCost";在这个例子中,Factory 模式用于基于产品类型创建不同类型的产品,而策略模式可用于计算每种产品的成本。
以上就是PHP 自函数编写中常用设计模式的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号