设计模式04:单例模式

来源:互联网 发布:百科门窗软件下载 编辑:程序博客网 时间:2024/06/06 17:55

单例模式,比较简单。UML如下
这里写图片描述

饿汉式:

public class Single {    private static Single single=new Single();    private Single(){}    public static Single getInstance(){        return single;    }}

懒汉式:方法体上需要加synchronized关键字

public class Singleton {      private static Singleton instance;      private Singleton (){}      public static synchronized Singleton getInstance() {      if (instance == null) {          instance = new Singleton();      }      return instance;      }  } 
0 0