PHP工厂模式的实现:
工厂模式是一种常用的面向对象设计模式,它通过定义一个工厂类来创建和返回其他对象的实例,而不需要直接使用new关键字实例化对象。以下是一个简单的PHP工厂模式的实现示例:
<?php// 定义一个接口interface Shape {public function draw();}// 实现接口的具体类class Circle implements Shape {public function draw() {echo "Drawing a circle\n";}}class Square implements Shape {public function draw() {echo "Drawing a square\n";}}// 定义一个工厂类class ShapeFactory {public static function createShape($type) {switch ($type) {case 'circle':return new Circle();case 'square':return new Square();default:throw new Exception("Unsupported shape type: $type");}}}// 使用工厂类创建对象$circle = ShapeFactory::createShape('circle');$circle->draw(); // 输出 "Drawing a circle"$square = ShapeFactory::createShape('square');$square->draw(); // 输出 "Drawing a square"单例模式的实现:
单例模式是一种常用的面向对象设计模式,它确保类只有一个实例,并提供全局访问该实例的方法。以下是一个简单的PHP单例模式的实现示例:
<?phpclass Database {private static $instance;private $connection;private function __construct() {// 私有构造函数,防止通过new关键字实例化类$this->connection = mysqli_connect('localhost', 'username', 'password', 'database');}public static function getInstance() {if (!self::$instance) {self::$instance = new Database();}return self::$instance;}public function getConnection() {return $this->connection;}}// 使用单例类获取数据库连接$db = Database::getInstance();$connection = $db->getConnection();// 使用$connection进行数据库操作在上面的示例中,Database类的构造函数是私有的,因此不能直接通过new关键字实例化类。通过getInstance()方法获取类的唯一实例,如果实例不存在,则创建一个新实例并返回,否则直接返回已存在的实例。通过getConnection()方法可以获取数据库连接对象,然后可以使用该连接对象进行数据库操作。