php-单例模式
2021/8/4 1:08:05
本文主要是介绍php-单例模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
php-单例模式
概述
单例模式(Singleton Pattern):确保某一个类只有一个实例且自行实例化并向整个系统提供这个实例,这个类称之为单例类,它提供全局访问的方法。
单例模式的要点有三个:
- 单例类必须自行向整个系统提供这个实例。
- 单例类只能有一个实例
- 单例类的实例必须由自己创建
代码范例
<?php class Singleton{ //用于保存实例 private static $instance; //防止外部创建实例 private function __construct(){} //防止复制实例 private function __clone(){} public $test_text; //公有方法,用于获取实例 public static function getInstance(){ //判断实例有无创建,没有的话创建实例并返回,有的话直接返回 if(!(self::$instance instanceof self)){ self::$instance = new self(); } return self::$instance; } public function setText(string $text){ $this->test_text = $text; } public function getText():string{ return $this->test_text; } } class Test{ public function __construct($text) { Singleton::getInstance()->setText($text); } function printText(){ echo Singleton::getInstance()->getText(); } } $test = new Test(12); echo $test->printText(); exit();
以上代码结果
模式分析
单例模式的目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点。单例模式包含的角色只有一个,就是单例类——Singleton。单例类拥有一个私有构造函数,私有克隆方法。确保无法通过外部直接实例化/克隆它。另外,单例模式中包含一个静态私有成员变量和静态公有的工厂方法,该工厂方法用于检测实例是否存在并实例化自己。然后存储在静态变量中。以确保只有一个实例被创建。
在实现单例模式的过程中,需要注意以下几点
- 单例类的构造函数,克隆函数为私有
- 提供一个自身的静态私有成员变量
- 提供一个公有的静态工厂方法
这篇关于php-单例模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-29env: php: no such file or directory
- 2024-03-01php foreach break
- 2024-02-26Exception参数 php-icode9专业技术文章分享
- 2023-12-30PHP文件批量上传-icode9专业技术文章分享
- 2023-12-30thinkphp6 withJoin-icode9专业技术文章分享
- 2023-12-27MagicArray:像php一样,让Go业务代码不再卷!
- 2023-11-18centos7编译安装PHP教程。
- 2023-11-18centos7编译安装phpMyAdmin教程。
- 2023-10-13唱衰这么多年,PHP 仍然还是你大爷!
- 2023-07-25PHP8,性能更好,语法更好,类型安全更完善