zoukankan      html  css  js  c++  java
  • 单实例模式

     

    单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

    1.什么时候需要单实例模式?

    整个类在系统运行过程中只允许一个对象,并且这个对象在整个系统的任何地方,都能够被随时随地的访问得到,并且所有的客户访问的都是同一个对象。

    2.怎么来做呢?

    三个要点:(1)你要定义一个私有化的构造函数

         (2)你要定义一个私有的成员变量

         (3)你要定义一个共有的get函数(所有的用户通过这个get函数都能够访问到唯一的这个单实例)

    单例类只能有一个实例。
    单例类必须自己创建自己的唯一实例。
    单例类必须给所有其他对象提供这一实例。

     

     

    1.单例模式——线程安全的饿汉模式

    public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){

    }
    public static Singleton getInstance(){
    return instance;
    }
    }

    2.单例模式——线程安全的懒汉模式 

    public class Singleton {
    private static Singleton instance = null;
    private Singleton(){

    }
      //如果不加synchronized,则是线程不安全的
    public static synchronized Singleton getInstance(){
    if(instance == null){
    instance = new Singleton();
    }
    return instance;
    }
    }

    3.单例模式——线程安全的懒汉模式改进版(双重检查锁)

    /**
    *双重锁:为了减少同步的开销
    */
    public class Singleton{
    // 静态可见的实例
    private static volatile Singleton instance = null;
    // 无参构造器
    private Singleton(){

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

    4.单例模式——私有的内部工厂类(线程安全)

    public class Singleton {
    private Singleton(){
    }

    public static Singleton getInstance(){
    return SingletonFactory.Instance;
    }

    private static class SingletonFactory{
    private static Singleton Instance = new Singleton();
    }
    }
    //内部类也可以换成内部接口,但是工厂类变量的作用域需为public
  • 相关阅读:
    Oracle db 使用转换函数和条件表达式
    Oracle DB 嵌套函数
    Oracle DB NVL、NVL2、NULLIF、COALESCE函数
    OCP-1Z0-051-V9.02-92题
    OCP-1Z0-051-V9.02-90题
    OCP-1Z0-051-V9.02-89题
    OCP-1Z0-051-V9.02-88题
    OCP-1Z0-051-V9.02-87题
    OCP-1Z0-051-V9.02-86题
    OCP-1Z0-051-V9.02-85题
  • 原文地址:https://www.cnblogs.com/cdlyy/p/12046618.html
Copyright © 2011-2022 走看看