单例模式中需要解决的重要问题是方法的同步问题,同步的粒度有多大等。在本例子中同在获得类的实例的时候使用了同步,代码如下:
public class Singleton{
private Singleton(){
generator = new Random();
}
public void setSeed(int seed){
generator.setSeed(seed);
}
public int nextInt(){
return generator.nextInt();
}
public static synchronized Singleton getInstance(){
if (instance == null) {
instance = new Singleton();
}
return instance;
}
private Random generator;
private static Singleton instance;
}
客户端调用的代码:
package singleton;
public class Client{
public static void main(String[] args){
Singleton s1 = Singleton.getInstance();
System.out.println(s1.toString());
for(int i=0;i<10;i++){
Singleton s2 = Singleton.getInstance();
System.out.println("The randomed number is "+s2.toString());
}
}
}
public class Singleton{
private Singleton(){
generator = new Random();
}
public void setSeed(int seed){
generator.setSeed(seed);
}
public int nextInt(){
return generator.nextInt();
}
public static synchronized Singleton getInstance(){
if (instance == null) {
instance = new Singleton();
}
return instance;
}
private Random generator;
private static Singleton instance;
}
客户端调用的代码:
package singleton;
public class Client{
public static void main(String[] args){
Singleton s1 = Singleton.getInstance();
System.out.println(s1.toString());
for(int i=0;i<10;i++){
Singleton s2 = Singleton.getInstance();
System.out.println("The randomed number is "+s2.toString());
}
}
}