其他分享
首页 > 其他分享> > 设计模式-单例模式code

设计模式-单例模式code

作者:互联网

package singeton;


import java.security.SecureRandom;

/**
* @author Zero
* @since 2019-08-13.
* Description:
*/
public class HungrySingleton {
private static final HungrySingleton singleton = new HungrySingleton();
private final int ID = new SecureRandom().nextInt();

private HungrySingleton() {
}

public static HungrySingleton getSingleton() {
return singleton;
}

public int doSomething() {
// System.out.println("I'm HungrySingeton " + ID + "!");
return ID;
}
}

package singeton;

import java.security.SecureRandom;

/**
* @author Zero
* @since 2019-08-13.
* Description:
*/
public class LazySingleton {
private static LazySingleton singeton = null;
private final int ID = new SecureRandom().nextInt();

private LazySingleton() {
}

public static synchronized LazySingleton getSingleton() {
if (singeton == null) {
singeton = new LazySingleton();
}
return singeton;
}

public int doSomething() {
// System.out.println("I'm LazySingeton " + ID + "!");
return ID;
}

}

标签:code,HungrySingleton,LazySingleton,private,ID,单例,singeton,设计模式,public
来源: https://www.cnblogs.com/DeskZero/p/11707388.html