单例模式的定义:类只有一个全局对象,构造函数私有化,提供一个对外获取单例对象的方法。
对于打印机,数据库连接池这些对象,全局应该仅有一个对象对应着一个实体。
代码示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class Singleton
{ //valatile关键字的作用是:防止编译器优化代码可能对该语句的修改,使其严格按照该指令执行 private volatile static Singleton
uniqueInstance = null ; private Singleton(){} public static Singleton
getInstance(){ if (uniqueInstance
== null ){ //防止多线程环境下,产生多个对象 synchronized (Singleton. class )
{ if (uniqueInstance
== null ){ uniqueInstance
= new Singleton(); } } } return uniqueInstance; } } |