Singleton Pattern(中文称单例模式),可以说是最容易理解的设计模式了,也充分体现了DRY
(Don't Repeat Yourself)的思想。
单例模式的核心思想是:保证一个对象存在且仅允许存在一个实例,并提供一个全局访问方式。
单例模式的运作模型是:当对象第一次被请求时,创建这个对象的实例;之后的每次请求,仅传递已创建实例的句柄。与单例模式相对应的模式叫做Prototype(Java平台下)或者叫SingleCall(.NET平台下),在此种模式下,每次请求一个对象,都将新建一个实例。
在WEB程序中应用单例模式的一个典型例子是数据库连接的创建:通过数据库句柄来连接数据库这一行为是独占的。换言之,在一个句柄尚未关闭之前,你无法第二次创建一个相同名称的句柄。然后在日常编码中,假设你希望在同一页面中操作由数据库传递回来的多组数据。此时如果采用传统的Prototype方式编程,为了程序的安全运行,你可能需要创建多个数据库链接句柄或者重复进行打开/关闭数据库连接的操作。显然,这样的操作会导致程序过度消耗一些不必要的资源。
在此场景下,我们可以运用单例模式来维护和共享同一个数据库句柄。优点有二:
1、提高了程序运行上的安全性。你不必过多的担心和考虑诸如数据库打开/关闭的问题。
2、避免了因创建多个连接导致的不必要资源浪费。垃圾回收机制仅需要对一个链接句柄进行操作。
当然,以上两个问题对于PHP来说并不是问题,PHP的垃圾回收机制就是:当一个页面执行完毕会自动清空所有资源和内存,这里面就包括数据库连接。
至此,可以总结出Singleton单例模式在WEB程序中的运用场合:
1、某些资源本身具有独占性,你不希望在多个地方重复创建对这个独占资源对象的实例。
2、你需要在同一个对象的实例的多个引用之间共享这个对象的状态(下面我会将此条规则进行代码举例)。
下面写一段小代码来演示PHP 5中Singleton的实现:
class Singleton
{
//此成员变量用来记录此对象的引用次数
private $counter = 1;
//注意这里是private,即禁止外部程序通过解析函数实例化对象
private function __construct()
{
}
//禁止克隆这个对象
private function __clone()
{
}
//必须通过此方法得到对象的引用
public static function getInstance()
{
static $instance = null;
if($instance == null)
{
$instance = new Singleton();
}
return $instance;
}
public function getUsedCount()
{
return $this->counter++;
}
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
