模式类型: 单例模式
应用场合: 有些对象只需要一个就够了
作用: 保证整个应用程序中某个实例只有一个
类型: 懒汉模式、饿汉模式
单例模式之饿汉模式Singleton |
package com.arika.singltonpattern;
/**
* 单例模式Singleton
* @author arika
*
*/
public class Singleton {
//1、将构造方法私有化, 不允许外部直接创建对象
private Singleton(){
}
//2、创建类的一个实例, 使用private static 修饰
private static Singleton instance = new Singleton();
//3、提供一个用于获取实例的方法, 用public static 修饰
public static Singleton getInstance(){
return instance;
}
}
|
单例模式之懒汉模式SingletonLazy |
package com.arika.singltonpattern;
/**
* 懒汉模式
* @author arika
*/
public class SingletonLazy {
//1、将构造方法私有化, 不允许外边直接创建对象
private SingletonLazy(){
}
//2、创建类的一个实例, 使用private static 修饰
private static SingletonLazy instance;
//3、提供一个用于获取实例的方法, 用public static 修饰
public static SingletonLazy getInstance(){
if(instance == null){
instance = new SingletonLazy();
}
return instance;
}
}
|
测试 |
package com.arika.singltonpattern;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//恶汉模式测试
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
if(s1 == s2){
System.out.println("s1 和 s2 是同一个实例 ");
} else {
System.out.println("s1 和 s2 不是同一个实例 ");
}
//懒汉模式测试
SingletonLazy s3 = SingletonLazy.getInstance();
SingletonLazy s4 = SingletonLazy.getInstance();
if(s3 == s4){
System.out.println("s3 和 s4 是同一个实例 ");
} else {
System.out.println("s3和 s4 不是同一个实例 ");
}
}
}
|
区别: 饿汉模式的特点是加载类时比较慢, 但运行时获取对象的速度比较快
饿汉模式的特点是加载时比较快, 但运行时获取对象的速度比较慢, 线程不安全
示例代码地址:
http://download.youkuaiyun.com/detail/jinfei95/8384507