转载请注明出处:单例设计模式_Mr_Leixiansheng的博客-CSDN博客
单例模式:特点只有一个对象(懒汉模式、饿汉模式)
步骤:
1、构造私有化
2、创建静态私有唯一实例(或者声明唯一实例)
3、提供获取实例方法(静态共有)
代码如下:
package com.leixiansheng;
/**
* 饿汉模式
* @author Administrator
*
*/
public class Singleton1 {
//1、构造方法私有
private Singleton1(){
}
//2、创建唯一实例
private static Singleton1 instance = new Singleton1();
//3、提供获取类方法
public static Singleton1 getInstance(){
return instance;
}
}
package com.leixiansheng;
/**
* 懒汉模式(推荐)
* @author Administrator
*
*/
public class Singleton2 {
//1、私有构造
private Singleton2(){
}
//2、声明唯一实例
private static Singleton2 instance;
//3、提供获取实例方法
public static Singleton2 getInstance(){
if(instance==null){
instance = new Singleton2();
}
return instance;
}
}
package com.leixiansheng;
public class SingleTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* 饿汉模式
*/
Singleton1 s1 = Singleton1.getInstance();
Singleton1 s2 = Singleton1.getInstance();
if(s1==s2){
System.out.println("s1和s2是同一个实例");
}else {
System.out.println("s1和s2不是同一个实例");
}
/**
* 懒汉模式
*/
Singleton2 s3 = Singleton2.getInstance();
Singleton2 s4 = Singleton2.getInstance();
if(s3==s4){
System.out.println("s3和s4是同一个实例");
}else {
System.out.println("s3和s4不是同一个实例");
}
}
}