Java之创建对象>3.Enforce the singleton property with a private constructor or an enum type详解编程语言
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.
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/15971.html
cjava相关文章
- JAVA对象转map_java处理字符串类型的map
- Java容器(三):LinkedList源码分析详解编程语言
- java生成随机数方法大全(可指定范围、分布方式、类型、种子)详解编程语言
- java贪吃蛇游戏代码详解编程语言
- Java 模拟HTTP Get Post请求详解编程语言
- Java处理XSS漏洞的工具类代码详解编程语言
- 将每三个数字加上逗号处理Java代码详解编程语言
- java按文件大小、名称、日期排序方法详解编程语言
- Java根据两点的经纬度来计算之间的距离详解编程语言
- Java 过滤html标签代码详解编程语言
- java多线程有几种实现方法线程之间如何同步详解编程语言
- Java学习笔记之十三初探Java面向对象的过程及代码实现详解编程语言
- java学习笔记11–Annotation详解编程语言
- java中的ThreadLocal详解编程语言
- java-jpa-criteriaBuilder使用入门详解编程语言
- java正则表达式笔记详解编程语言
- java获取指定文件夹下的所有文件名详解编程语言
- java 线程 Lock 锁使用Condition实现线程的等待(await)与通知(signal)详解编程语言
- JedisConnectionException: java.net.SocketException: Socket closed;Unknown reply: ; It seems like server has closed the connection.解决办法详解编程语言
- 一个java删除文件夹的小方法详解编程语言
- JAVA操作字符串详解编程语言
- RSA加密和数字签名在Java中常见应用【原创】详解编程语言