关于java的单例模式

经典的单例模式

Demo one

public class Singleton {

    private static Singleton uniqueInstance = null;

 

    private Singleton() {

       // Exists only to defeat instantiation.

    }

 

    public static Singleton getInstance() {

       if (uniqueInstance == null) {

           uniqueInstance = new Singleton();

       }

       return uniqueInstance;

    }

    // Other methods...

}

注册式的单例模式

Demo one


 1 import java.util.HashMap;
 2 import java.util.Map;
 3 //登记式单例类.
 4 //类似Spring里面的方法,将类名注册,下次从里面直接获取。
 5 public class Singleton3 {
 6     private static Map<String,Singleton3> map = new HashMap<String,Singleton3>();
 7     static{
 8         Singleton3 single = new Singleton3();
 9         map.put(single.getClass().getName(), single);
10     }
11     //保护的默认构造子
12     protected Singleton3(){}
13     //静态工厂方法,返还此类惟一的实例
14     public static Singleton3 getInstance(String name) {
15         if(name == null) {
16             name = Singleton3.class.getName();
17             System.out.println("name == null"+"--->name="+name);
18         }
19         if(map.get(name) == null) {
20             try {
21                 map.put(name, (Singleton3) Class.forName(name).newInstance());
22             } catch (InstantiationException e) {
23                 e.printStackTrace();
24             } catch (IllegalAccessException e) {
25                 e.printStackTrace();
26             } catch (ClassNotFoundException e) {
27                 e.printStackTrace();
28             }
29         }
30         return map.get(name);
31     }
32     //一个示意性的商业方法
33     public String about() {    
34         return "Hello, I am RegSingleton.";    
35     }    
36     public static void main(String[] args) {
37         Singleton3 single3 = Singleton3.getInstance(null);
38         System.out.println(single3.about());
39     }
40 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值