代码如下:
package leotoneo;
//先付上饿汗单例设计模式
class Single {
//创建私有化对象
private static Single s = new Single();
//私有化构造函数
private Single() {
}
//在静态对象中返回创建的私有化对象
public static Single getInstance() {
return s;
}
}
public class SingleDesign {
//记录本类产生对象的个数
public static int count = 0;
//一 声明本类引用类型变量 但是不要new
private static SingleDesign singleDesign;
//二 构造函数私有化
private SingleDesign(){
}
//三 定义产生对象的静态方法
public static SingleDesign createOnly(){
if(singleDesign == null){
synchronized ("锁") {
if(singleDesign ==null){
singleDesign = new SingleDesign();
count++;
}
}
}
return singleDesign;
}
public static void main(String[] args){
SingleDesign s1 = SingleDesign.createOnly();
SingleDesign s2 = SingleDesign.createOnly();
System.out.println(count);
}
}