一个类只有一个实例对象
1、含义
作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统全局的提供这个实例。它不会创建实例副本,而是会向单例类内部存储的实例返回一个引用。
2、单例模式的三个要点
1)、一个类的唯一实例的静态成员变量:
private static $instance;
2)、构造函数和克隆函数必须声明为私有的,防止外部程序new类从而失去单例模式的意义:
private function __construct()
{
}
private function __clone()
{
}
3)、必须提供提供一个访问这个实例的公共的静态方法(一般为getInstance方法),从而返回唯一实例的一个引用:
public static function getInstance()
{
if (static::$instance == null) //或者 if (!(self::$_instance instanceof self))
{
static::$instance == new Self();
}
return static::$instance;
}
测试demo:
<?php
class Singleton
{
private static $instance;
private function __construct(){}
public static function getInstance()
{
if (static::$instance == null)
{
static::$instance == new Singleton();
}
return static::$instance;
}
}
//客户端代码
$s1 = Singleton::getInstance();
$s2 = Singleton::getInstance();
if ($s1 == $2)
{
echo "same class";
}
总结:
单例模式,保证一个类仅有一个实例,并提供一个访问它的全局访问点。使用单例模式可以避免大量的new操作,因为每一次new操作都会消耗系统和内存的资源。
单例模式因为Singleton类封装它的唯一实例,这样它可以严格的控制客户怎样访问以及何时访问它,简单来说就是对唯一实例的受控访问。
原文:https://www.cnblogs.com/lees410/p/10416537.html