单例模式

  单例模式的定义:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

  以下提供两种简单的实现方式:

 1 package org.zxx.designPatterns;
 2 
 3 /**
 4  * 
 5  * @author zxx
 6  * @Apr 19, 2013
 7  */
 8 public class SingletonOne {
 9     private static SingletonOne singleton=null;
10     private SingletonOne(){
11     }
12     /**
13      * 此方法线程不安全,当多个线程访问时会产生不止一个当前类的实例
14      * @return
15      */
16     public static SingletonOne getInstance(){
17         if(singleton==null){
18             singleton=new SingletonOne();
19         }
20         return singleton;
21     }
22 }
 1 package org.zxx.designPatterns;
 2 
 3 /**
 4  * @author zxx
 5  * @Apr 19, 2013
 6  */
 7 public class SingletonTwo {
 8     private static final SingletonTwo singleton = new SingletonTwo();
 9     
10     private SingletonTwo() {
11     }
12     
13     /**
14      * 此方法线程安全,当多个线程访问时访问的都是同一个静态实例singleton
15      * @return
16      */
17     public static SingletonTwo getInstance() {
18         return singleton;
19     }
20 }
原文地址:https://www.cnblogs.com/Lucas4J/p/3031584.html