单例模式 发表于 2018-03-31 | 更新于: 2018-03-31 | 分类于 设计模式 | | 阅读次数: | 字数统计: 484 | 阅读时长 ≈ 3 单例模式(Singleton Pattern)属于创建型模式,此模式涉及单一的类与对象,类负责创建自己的对象,同时保证只有一个对象被使用。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141/* * Copyright,ShanNong Inc,2018 and onwards * * Author:fanghua fan */package com.fanghua.designpattrn.singleton;/** * 单例模式, 线程不安全模式 */public class SingletonPattern { private static SingletonPattern object; private SingletonPattern() { } /** * 获取单利对象 * * @return */ private static SingletonPattern getInstance() { if (object == null) { object = new SingletonPattern(); } return object; } private void showInstance() { System.out.println("show instance:" + getClass().hashCode()); } public static void main(String[] args) { for (int i = 0; i < 100; i++) SingletonPattern.getInstance().showInstance(); }}/** * 线程安全式 */class SingletonPatternSafe { private static SingletonPatternSafe object; private SingletonPatternSafe() { } /** * 获取单利对象 * * @return */ private static synchronized SingletonPatternSafe getInstance() { if (object == null) { object = new SingletonPatternSafe(); } return object; } private void showInstance() { System.out.println("show instance:" + getClass().hashCode()); } public static void main(String[] args) { for (int i = 0; i < 100; i++) SingletonPatternSafe.getInstance().showInstance(); }}/** * 线程安全,但是浪费内存 */class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; }}/** * 基于双重校验锁的线程安全式 */class SingletonDoubleLock { private volatile static SingletonDoubleLock singleton; private SingletonDoubleLock() { } public static SingletonDoubleLock getSingleton() { if (singleton == null) { synchronized (SingletonDoubleLock.class) { if (singleton == null) { singleton = new SingletonDoubleLock(); } } } return singleton; }}/** * 基于内部类的线程安全式单例模式 */class SingletonInnerStatic { private static class SingletonHolder { private static final SingletonInnerStatic INSTANCE = new SingletonInnerStatic(); } private SingletonInnerStatic() { } public static final SingletonInnerStatic getInstance() { return SingletonHolder.INSTANCE; }}/** * 单元素的枚举类型是singleton实现的最佳方法,同时也是线程安全的 */class ObjectResource {}enum SomeThing { INSTANCE; private ObjectResource instance; SomeThing() { instance = new ObjectResource(); } public ObjectResource getInstance() { return instance; }} (全文完)3/31/2018 10:05:32 PM 本文作者: 南风 本文链接: http://www.jackfan.top/posts/60114/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!