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

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

  模式意图

  保证类仅有一个实例,并且可以供应用程序全局使用。为了保证这一点,就需要这个类自己创建自己的对象,并且对外有公开的调用方法。

  模式结构

  Singleton 单例类,内部包含一个本身的对象。并且构造方法时私有的。

  使用场景

  当类只有一个实例,而且可以从一个固定的访问点访问它时。

  代码结构

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

 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 }

 

posted @ 2014-10-26 20:40  xingoo  阅读(1619)  评论(0编辑  收藏  举报