1.最简单的单例模式:
2.线程不安全的单例模式
3.线程安全的单例模式
4.内部类单例模式
package com.singleton;
/**这是最简单的单例模式,实现的效果的是在一个jvm中只有一个实例
* 类在加载的时候静态变量只会初始化一次。
* 1.这种模式的问题在于不能够延迟加载,当SimpleSingleton加载到内存的时候
* 实例就会自动生成,不能够延迟加载
*
*/
public class SimpleSingleton {
private SimpleSingleton(){};
private static SimpleSingleton instance=new SimpleSingleton();
public static SimpleSingleton getInstance()
{
return instance;
}
public static void main(String[] args)
{
SimpleSingleton s1=SimpleSingleton.getInstance();
SimpleSingleton s2=SimpleSingleton.getInstance();
System.out.println(s1==s1);
System.out.println(s1.equals(s2));
}
}
2.线程不安全的单例模式
package com.singleton;
/**
* 这里实现了延迟加载的目的,但是却不是线程安全的
* 原因主要在于两个线程同时到判断是否为null的时候
* 可能一起创建实例
* @author Administrator
*
*/
public class UnThreadSingleton {
private static UnThreadSingleton instance;
public static UnThreadSingleton getInstance()
{
if(instance==null)
{
instance=new UnThreadSingleton();
}
return instance;
}
public static void main(String[] args)
{
UnThreadSingleton s1=UnThreadSingleton.getInstance();
UnThreadSingleton s2=UnThreadSingleton.getInstance();
System.out.println(s1==s2);
}
}
3.线程安全的单例模式
package com.singleton;
public class ThreadSingleton {
public static ThreadSingleton instance;
public static ThreadSingleton getInstance()
{
if(instance==null)
synchronized(ThreadSingleton.class){
if(instance==null)
{
instance=new ThreadSingleton();
}
}
return instance;
}
public static void main(String[] args)
{
ThreadSingleton t1=ThreadSingleton.getInstance();
ThreadSingleton t2=ThreadSingleton.getInstance();
System.out.println(t1==t2);
}
}
4.内部类单例模式
package com.singleton;
public class LazyLoadSingleton {
private static class LazyHolder
{
private static LazyLoadSingleton singletonInstance=new LazyLoadSingleton();
}
public static LazyLoadSingleton getInstance()
{
return LazyHolder.singletonInstance;
}
public static void main(String[] args)
{
LazyLoadSingleton l1=LazyLoadSingleton.getInstance();
LazyLoadSingleton l2=LazyLoadSingleton.getInstance();
System.out.println(l1==l2);
}
}