美文网首页技术栈
2019-02-21——设计模式 单例模式

2019-02-21——设计模式 单例模式

作者: 烟雨乱平生 | 来源:发表于2019-02-21 00:58 被阅读0次

特点

某个类只能有一个实例,提供一个全局的访问点

实现

1. 采用静态属性,饿汉模式
缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。

public class SingleInstance {
    private SingleInstance(){}
    public static SingleInstance instance = new SingleInstance();
}

几种变形:

  • 使用静态常量
public class SingleInstance {
    private SingleInstance(){}
    private final static SingleInstance instance = new SingleInstance();
    public static SingleInstance getInstance(){
        return instance;
    }
}
  • 使用静态代码块
public class SingleInstance {
    private SingleInstance(){}
    private static SingleInstance instance;
    static {
        instance = new SingleInstance();
    }
    public static SingleInstance getInstance(){
        return instance;
    }
}

2.使用内部锁,懒汉模式
缺点:率太低了,每个线程在想获得类的实例时候,都需要执行同步方法

public class SingleInstance {
    private SingleInstance(){}
    private static SingleInstance instance;
    public synchronized static SingleInstance getInstance(){
        return new SingleInstance();
    }
}

3.使用双重检查,懒汉模式

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

4.静态内部类

public class SingleInstance {
    private SingleInstance(){}

    public static SingleInstance getInstance(){
        return InnerClass.instance;
    }

    static class InnerClass{
        private static SingleInstance instance = new SingleInstance();
    }
}

5.使用枚举

public enum SingleInstance {
    INSTANCE
    ;
    public static void metod(){}
}

相关文章

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • 单例模式: Singleton

    时间: 2019-02-21 参考地址: 单例模式的八种写法比较 一、单例模式的实现思路 Singleton类只会...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 基础设计模式:单例模式+工厂模式+注册树模式

    基础设计模式:单例模式+工厂模式+注册树模式 单例模式: 通过提供自身共享实例的访问,单例设计模式用于限制特定对象...

  • 单例模式

    JAVA设计模式之单例模式 十种常用的设计模式 概念: java中单例模式是一种常见的设计模式,单例模式的写法...

网友评论

    本文标题:2019-02-21——设计模式 单例模式

    本文链接:https://www.haomeiwen.com/subject/qrdyeqtx.html