【设计模式】—— 单例模式Singleton

  前言:【模式总览】——————————by xingoohtml

  模式意图

  保证类仅有一个实例,而且能够供应用程序全局使用。为了保证这一点,就须要这个类本身建立本身的对象,而且对外有公开的调用方法。函数

  模式结构

  Singleton 单例类,内部包含一个自己的对象。而且构造方法时私有的。spa

  使用场景

  当类只有一个实例,并且能够从一个固定的访问点访问它时。code

  代码结构

  【饿汉模式】经过定义Static 变量,在类加载时,静态变量被初始化。htm

 1 package com.xingoo.eagerSingleton;  2 class Singleton{  3     private static final Singleton singleton = new Singleton();  4     /**  5  * 私有构造函数  6      */
 7     private Singleton(){  8         
 9  } 10     /** 11  * 得到实例 12  * @return 13      */
14     public static Singleton getInstance(){ 15         return singleton; 16  } 17 } 18 public class test { 19     public static void main(String[] args){ 20  Singleton.getInstance(); 21  } 22 }

 

  【懒汉模式】对象

 1 package com.xingoo.lazySingleton;  2 class Singleton{  3     private static Singleton singleton = null;  4     
 5     private Singleton(){  6         
 7  }  8     /**  9  * 同步方式,当须要实例的才去建立 10  * @return 11      */
12     public static synchronized Singleton getInstatnce(){ 13         if(singleton == null){ 14             singleton = new Singleton(); 15  } 16         return singleton; 17  } 18 } 19 public class test { 20     public static void main(String[] args){ 21  Singleton.getInstatnce(); 22  } 23 }
相关文章
相关标签/搜索