zoukankan      html  css  js  c++  java
  • Singleton Summary

    Java Singleton:

    Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.

    The singleton class must provide a global access point to get the instance of the class.
    Singleton pattern is used for logging, drivers objects, caching and thread pool.

    Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. Singleton design pattern is used in core java classes also,for example, java.lang.Runtime, java.awt.Desktop.

    Java Singleton pattern

    To implement Singleton pattern, there are different approaches but all of them have following common concepts.

    1. Private constructor to restrict instantiation of the class from other classes.
    2. Private static variable of the same class that is the only instance of the class.
    3. Public static method that returns the istance of the class, this is the global access point for outer would to get the instance of the singleton class.

    Different approaches of Singleton pattern implementation and design concerns with the implementation.

    1. Eager initialization
    2. Static block initialization
    3. Lazy Initialization
    4. Thread Safe Singleton
    5. Bill Pugh Singleton Implementation
    6. Using Reflection to destroy Singleton Pattern
    7. Enum Singleton
    8. Serialization and Singleton


    Eager initialization:
    In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.

    public class EagerInitializedSingleton{
          private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
          //private constructor to avoid client applications to use constructor
          private EagerInitializedSingleton(){}
          public static EagerInitializedSingleton getInstance(){
                  return instance;
            }
    }

  • 相关阅读:
    2019.8.6原型链与继承
    2019.8.2闭包,作用域
    2019.8.1正则二
    2019.7.31正则
    2019.7.29二维数组
    2019.7.28关于数组和循环的八道题
    2019.7.27数组api
    DOM
    JavaScript数组5种去重方法
    JavaScript面向对象
  • 原文地址:https://www.cnblogs.com/heylinart/p/7058698.html
Copyright © 2011-2022 走看看