单例模式

来源:互联网 发布:域名转出流程 编辑:程序博客网 时间:2024/05/16 02:02

概念

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例

Java实现

  • 饿汉模式
package com.billJiang.pattern.singleton;/** * Created by billJiang on 2016/10/22. */public class SingletonEager {    private SingletonEager() {    }    private static SingletonEager singletonEager=new SingletonEager();    public static SingletonEager getInstance(){        return singletonEager;    }}
  • 懒汉模式
package com.billJiang.pattern.singleton;/** * Created by billJiang on 2016/10/22. */public class SingletonLazy {    private SingletonLazy() {    }    private static SingletonLazy instance = null;    public static synchronized SingletonLazy getInstance() {        if (instance == null)            instance = new SingletonLazy();        return instance;    }}
  • 测试
package com.billJiang.pattern.singleton;/** * Created by billJiang on 2016/10/22. */public class Client {    public static void main(String[] args) {        SingletonEager singletonEager_1=SingletonEager.getInstance();        SingletonEager singletonEager_2=SingletonEager.getInstance();        System.out.println(singletonEager_1==singletonEager_2);        SingletonLazy singletonLazy_1=SingletonLazy.getInstance();        SingletonLazy singletonLazy_2=SingletonLazy.getInstance();        System.out.println(singletonLazy_1==singletonLazy_2);    }}
0 0
原创粉丝点击