- //饿汉式:只要加载类就创建本类的实例
- class Single
- {
- private static single s = new Single();//定义本类的实例
- private Single(){};//拒绝访问本类构造函数,也就不能用new创建本类对象
- public static Single getInstance()//提供外部访问的方法
- {
- return s;
- }
- }
- //懒汉式:调用getInstance才会创建实例,之前为空
- class Single2
- {
- private static Single2 s = null;
- private Single2(){};
- public static Single getInstance()
- {
- if (s==null)
- s = new Single2();
- return s;
- }
- }
复制代码
|
|