php工厂模式和单例模式怎么实现

avatar
作者
猴君
阅读量:0

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单例模式的实现示例:

<?php class 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()方法可以获取数据库连接对象,然后可以使用该连接对象进行数据库操作。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!