zoukankan      html  css  js  c++  java
  • Java之创建对象>3.Enforce the singleton property with a private constructor or an enum type

     1. 通过一个公开的字段来获取单例

    // Singleton with public final field
    public class Elvis {
        public static final Elvis INSTANCE = new Elvis();
        private Elvis() { ... }
        public void leaveTheBuilding() { ... }
    }

    The main advantage of the public field approach is that the declarations make it clear that the class is a singleton: the public static field is final, so it will always contain the same object reference. There is no longer any performance advantage to the public field approach (没有任何性能优势)

    2. 通过一个公开的方法getInstance()来获取单例

     
    // Singleton with static factory
    public class Elvis {
        private static final Elvis INSTANCE = new Elvis();
        private Elvis() { ... }
        public static Elvis getInstance() { return INSTANCE; }
        public void leaveTheBuilding() { ... }
    }

    One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types. Often neither of these advantages is relevant, and the final-field approach is simpler.

    3.通过枚举来实现

    // Enum singleton - the preferred approach
    public enum Elvis {
        INSTANCE;
        public void leaveTheBuilding() { ... }
    }

     While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

  • 相关阅读:
    第09组(71) Alpha冲刺 (3/6)
    第09组 Alpha冲刺 (2/6)
    第09组 Alpha冲刺 (1/6)
    第09组(71)需求分析报告
    第07组 Beta冲刺(1/5)
    第07组 Alpha冲刺 总结
    第07组 Alpha冲刺 (6/6)
    第07组 Alpha冲刺 (5/6)
    第五次作业
    第07组 Alpha冲刺 (4/6)
  • 原文地址:https://www.cnblogs.com/frankyou/p/6913271.html
Copyright © 2011-2022 走看看