欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

设计模式-单例模式code

程序员文章站 2022-04-01 18:12:05
package singeton;import java.security.SecureRandom;/** * @author Zero * @since 2019-08-13. * Description: */public class HungrySingleton { private sta ......
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;
}

}