首页 > 编程 > Java > 正文

java 单例设计模式

2019-11-11 01:13:14
字体:
来源:转载
供稿:网友
/**  * 方法一 * 单例模式的实现:饿汉式,线程安全 但效率比较低  */  public class SingletonTest {      // 定义一个私有的构造方法    PRivate SingletonTest() {      }      // 将自身的实例对象设置为一个属性,并加上Static和final修饰符    private static final SingletonTest instance = new SingletonTest();      // 静态方法返回该类的实例    public static SingletonTest getInstancei() {          return instance;      }    

}

/**   *方法二 * 单例模式的实现:饱汉式,非线程安全    *    */  public class SingletonTest {    // 定义私有构造方法(防止通过 new SingletonTest()去实例化)    private SingletonTest() {       }       // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)    private static SingletonTest instance;       // 定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题)    public static SingletonTest getInstance() {           if (instance == null)               instance = new SingletonTest();           return instance;       }   } 
/**   *方法三 * 单例模式的实现:饱汉式,线程安全简单实现    *    */  public class SingletonTest {    // 定义私有构造方法(防止通过 new SingletonTest()去实例化)    private SingletonTest() {       }       // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)    private static SingletonTest instance;       // 定义一个静态的方法(调用时再初始化SingletonTest,使用synchronized 避免多线程访问时,可能造成重的复初始化问题)    public static synchronized  SingletonTest getInstance() {           if (instance == null)               instance = new SingletonTest();           return instance;       }   } 
/**   * 方法四 * 单例模式最优方案 * 线程安全  并且效率高   *   */
public class SingletonTest {     // 定义一个私有构造方法    private SingletonTest() {          }       //定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)    private static volatile SingletonTest instance;      //定义一个共有的静态方法,返回该类型实例    public static SingletonTest getIstance() {         // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率)        if (instance == null) {            //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)            synchronized (SingletonTest.class) {                //未初始化,则初始instance变量                if (instance == null) {                    instance = new SingletonTest();                   }               }           }           return instance;       }   }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表