用两种方式实现单实例(Java版)

来源:互联网 发布:js赋值给input 编辑:程序博客网 时间:2024/05/22 06:20

单实例的设计思想的目的是确保某个类在内存中只能有一个对象(实例)

单例模式的优点:既然只能有一个类对象,可以节约系统资源。

单例模式的使用场景:如果需要频繁创建和销毁这个类的对象,可以使用单例模式提高系统的性能。


有两种方式实现单实例:饿汉式、懒汉式。

饿汉式是先主动地创建实例提供给外界使用,懒汉式是外界调用时才提供(不主动提供)。

为了避免线程不安全问题,懒汉式的写法使用了线程同步代码块来确保只生成一个实例。

代码实现如下:



package singleton;


//Hungry Mode to generate a singleton instance.

//饿汉方式(主动式)实现单实例, 不适合多线程并发执行

class CourtJustice {

private CourtJustice() {}


private static CourtJustice justicInstance = new CourtJustice();


public static CourtJustice getJusticInstance() { // 通过一个公共的方法提供给外界访问

return justicInstance;

}

}


// Lazy Mode to generate a singleton instance.

// 懒汉式(被动式)实现单实例,下面的写法能避免线程不安全问题

class Jury {

private static Jury instance;


private Jury() {}


public static Jury getJuryObj() {

if (instance == null) { // 没有实例就不执行此代码块,提高程序性能

synchronized (Jury.class) { // 以当前类的描述符为锁

if (instance == null) {

instance = new Jury();

}

}

}

return instance;

}

}


public class SingletonDemo {

public static void main(String[] args) {

CourtJustice h1 = CourtJustice.getJusticInstance();

CourtJustice h2 = CourtJustice.getJusticInstance();

System.out.println("h1 == h2 : " + (h1 == h2));


Jury j1 = Jury.getJuryObj();

Jury j2 = Jury.getJuryObj();

System.out.println("j1 == j2 :" + (j1 == j2));

}

}



执行结果

h1 == h2 : true
j1 == j2 :true

可以看出h1和h2是同一对象,j1和j2是同一对象。成功实现了单实例。

0 0
原创粉丝点击