----------------------------------------------类------------------------------------------------
public class MySingLeton {
/**
* 一个静态变量指向自己
*/
private static MySingLeton instance = null;
/**
* 私有构造器保证不能从外部创建对象。
*/
private MySingLeton() {
}
/**
* 一个静态方法返回实例对象
* @return
*/
public static MySingLeton getInstance() {
if (instance == null) {
instance = new MySingLeton();
}
return instance;
}
}
----------------------------------------------测试------------------------------------------------
public class TestMySingLeton {
public static void main(String[] args) {
MySingLeton mySingLeton=MySingLeton.getInstance();
MySingLeton mySingLeton1=MySingLeton.getInstance();
System.out.println(mySingLeton);
System.out.println(mySingLeton1);
}
}
----------------------------------------------结果------------------------------------------------
com.demo.MySingLeton@4f1d0d
com.demo.MySingLeton@4f1d0d