设计模式-单例模式

来源:互联网 发布:me3630 软件 用户手册 编辑:程序博客网 时间:2024/05/22 06:41
 单例模式Singleton 
 应用场合:有些对象只需要一个就足够了,如古代皇帝,老婆 

 作用:保证整个应用程序中某个示例有且只有一个 类型:懒汉式,饿汉式 

代码实现-懒汉式


public class Singleton2 { // 懒汉式
// 1,将构造方法私有化,不允许外界直接创建对象
private Singleton2() {

}
// 2,声明类的唯一实例 使用private static
// private私有的 static类的静态成员 归类所有
// 当类加载的时候没有去new对象实例 只有当用获取时才判断是否去创建对象实例,
// 懒汉式--- 只有第一个用户获取时才去创建实例,以后获取时实例已经存在了就不会再去创建
private static Singleton2 instance;


// 3,提供一个用于获取实例的方法 public static
public static Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}


return instance;
}
}

代码实现-饿汉式

public class Singleton { // 饿汉式
// 1,将构造方法私有化,不允许外界直接创建对象
private Singleton() {


}


// 2,保证创建类的示例时是唯一的,使用private static
// private私有的 static类的静态成员 归类所有
// static类的静态成员 归类所有 不管用户是否需要,只要类加载,就会去创建该单例模式的对象nSingleton,即假设总是处于饥饿状态
private static Singleton instance = new Singleton();


// 3,提供一个用于获取实例的方法 public static
public static Singleton getInstance() {


return instance;
}
}


测试类代码实现:

public class Test {
public void main(String args[]) {
// 饿汉式
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
if (s1 == s2) {
System.out.println("s1和2是同一实例");
} else {
System.out.println("s1和2不是同一实例");
}
// 懒汉式
Singleton s3 = Singleton.getInstance();
Singleton s4 = Singleton.getInstance();


if (s3 == s4) {
System.out.println("s3和s4是同一实例");
} else {
System.out.println("s3和s4不是同一实例");
}


}
}

0 0
原创粉丝点击