广东书法高强:谁来帮帮我,JAVA问题

来源:百度文库 编辑:高考问答 时间:2024/04/28 23:31:04
谁帮小弟写一个Singleton出来,感激不尽!

public class Singleton {
private static Singleton instance = null;
public static synchronized Singleton getInstance() {
if (instance==null)
instance=new Singleton();
return instance; }
}

public class SingletonPattern
{
private double r;
//定义一个私有,静态的引用变量
private static SingletonPattern sp;
//构造器私有
private SingletonPattern()
{
r = java.lang.Math.random();
}
//提供一个共有,静态方法获得唯一实例
public static SingletonPattern getInstance()
{
if(sp==null)//如果还未创建实例
{
sp = new SingletonPattern();
}
return sp;
}

public double getR()
{
return r;
}

public static void main(String args[])
{
SingletonPattern sp1 =
SingletonPattern.getInstance();

SingletonPattern sp2 =
SingletonPattern.getInstance();

System.out.println(sp1.getR());
System.out.println(sp2.getR());
}
}

class Singleton {
private static Singleton instance;
private static Object Lock = new Object(); private Singleton() { }
public static Singleton getInstance() {
if (instance == null) { synthorized(Lock) {
if (instance == null) { instance = new Singleton(); }
}
}
return instance;
}
} Singleton的特点是由类自己来保证实例的唯一