所谓的单例模式就是系统中只存在一个类的实例。
为什么要使用单例模式
在一些程序中存在着对该程序的管理对象,一般一个程序管理对象只有一个
所以单例模式就出现了
如何实现单例模式
单例模式实现之一
//不好的实现方式1 仅能保证在单线程下运行
public class Q1_Singleton {
// 阻止创建单例对象
private Q1_Singleton() {
}
// 创建静态单例对象
private static Q1_Singleton singleton = null;
public static Q1_Singleton getSingleton() {
// 如果单例对象已经存在则创建否则不创建
if (singleton == null) {
return new Q1_Singleton();
}
return singleton;
}
}
单例实现方式二
/*
* 多线程条件下 多个进程同时判断singleton是否为null,
* 而此时singleton没有创建 此时就会生产多个singleton对象
* 为了保证单例模式可以在多线程条件下运行就需要给函数同步
*/
class Singleton1 {
private Singleton1() {
}
// 创建单例对象
private static Singleton1 singleton1 = null;
//同步
public static synchronized Singleton1 getSingleton() {
if (singleton1 == null)
return new Singleton1();
return singleton1;
}
}
单例模式实现三
/*
* 上个单例不完美 每次获取单例对象时都需要同步,
* 同步的目的防止在由于多线程导致创建多个单例对象 所以如果单例对象已经创建,根本不需要同步
* 为了解决这个问题我们先对单例对象是否已经创建进行判断
*/
class Singleton2 {
private Singleton2() {
}
// 创建单例对象
private static Singleton2 singleton2 = null;
public static Singleton2 getSingleton() {
// 先判断是否存在
if (singleton2 == null) {
// 同步
synchronized (Singleton2.class) {
// 同步后在判断是否创建
if (singleton2 == null) {
return new Singleton2();
}
return singleton2;
}
}
return singleton2;
}
}
单例模式实现四
/*
* 同步会使程序付出额外的开销
* Java中的静态变量只会在该类加载入虚拟机时创建一次
* 所以利用静态变量实现单例是非常合适的
*/
class Singleton3 {
private Singleton3() {
}
//只加载一次
private static Singleton3 singleton3 = new Singleton3();
public static Singleton3 getSingleton() {
return singleton3;
}
}
单例模式实现五
/*
* Singleton3的缺点是一加载此类就创建单例对象 不管是否会使用它
* 为了使单例对象按需创建,我们使用内部类,
*/
class Singleton4 {
private Singleton4() {
}
//只有调用getSingleton方法时才创建Singleton4对象
public static Singleton4 getSingleton() {
return staticSingleton.singleton4;
}
private static class staticSingleton {
static Singleton4 singleton4 = new Singleton4();
}
}
至此单例模式的实现就差不多了,若有错误,欢迎指正。