1.用作全局变量,可以作为一个Cache;
例如:要获取一个URL服务器请求host,可以通过HttpRequestServerlet**.java获得host,并将其保存在单例实例中,可以供项目直接调用。
2.一个简单的单例Test类,测试如下:
public class Test {
private String str = "abc";
private Test(){}
private static class Inner{
private static final Test test = new Test();
}
public static Test getInstance(){
return Inner.test;
}
public void setStr(String s){
this.str = s;
}
public static void main(String[] args) throws InterruptedException {
// String a = Base64.encodeBase64String(DigestUtils.md5Hex(System.currentTimeMillis() + "abc").getBytes());
// System.out.println(a + ".zip");
Test a = Test.getInstance();
System.out.println(a);//Test@3581c5f3
a.setStr("AAA");//
Thread.sleep(1000);
Test b = Test.getInstance();
System.out.println(b);//Test@3581c5f3
System.out.println(b.str);//AAA
Thread.sleep(1000);
/*下面两个示例可以验证单例模式。*/
Test c = new Test();
System.out.println(c.str); //abc
c.setStr("BBB"); // 设置无效!!
Test d = Test.getInstance();
System.out.println(d.str);//AAA 依旧是AAA,所以Test c的创建无法在项目下起作用。
}
}