public final class Singleton
{
private static String name;
private static String sex;
private static int age;
private static Singleton s = null;
private Singleton(String name, String sex, int age){ // 构造方法
this.name = name;
this.sex = sex;
this.age = age;
}
public static Singleton getInstance(String name, String sex, int age){
if(s==null){
synchronized(Singleton.class){
if(s==null)
s=new Singleton(name,sex,age);
}
}
return s;
}
public String toString(){
return("姓名="+name+"\n性别="+sex+"\n年龄="+age);
}
public static void main(String[] args)
{
Singleton sg1 = Singleton.getInstance("张三","男",20);
Singleton sg2 = Singleton.getInstance("李四","男",21);
System.out.println(sg1);
System.out.println(sg2);
}
}
多线程的应该可以直接调用这个类也能用 但是多线程貌似饿汉式比较好 这个延迟加载有点蛋疼 |
|