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;
            }
    }

  • 相关阅读:
    webapi之fiddler头设置
    ios---setContentOffset
    webapi参数处理get过个参数
    socket网络编程
    logging模块
    configparser模块(拷贝)
    hashlib模块--摘要算法
    异常处理
    面向对象拓展
    反射
  • 原文地址:https://www.cnblogs.com/heylinart/p/7058698.html
Copyright © 2011-2022 走看看