A class can be made noninstantiable by including a private constructor. // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } ... //…
Item4:Enforce noninstantiability with a private constructor 通过构造私有化,禁止对象被实例化. public class UtilClass { private UtilClass(){ //防止类内的函数调用构造函数创建对象 throw new AssertionError(); } }…
如果你定义的类仅仅是包含了一些静态的方法和静态的字段,这些类一般是一些工具类,这些一般是设计为不能被实例化的. 1. Attempting to enforce noninstantiability by making a class abstract does not work. 2. a class can be made noninstantiable by including a private constructor // Noninstantiable utility class p…
Principle When implement the singleton pattern please decorate the INSTANCE field with "static final" and decorate the constructor with "private". // Singleton with static factory public class Elvis { private static final Elvis INSTANC…
Item3:Enforce the singleton property with a private constructor or an enum type 采用枚举类型(ENUM)实现单例模式. public enum Elvis { INSTANCE; public void leaveTheBuiding(){ System.out.println("a single-element enum type is the best way to implement a singleton&q…
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st language I have chosen for this migration. It's a nice chance to read some great books like "Effective Java 2nd Edition" and share the note for what I…
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Objects Consider static factory methods instead of constructors (factory方法可以拥有名称,可以避免重复创建,比如单例模式) Consider a builder when faced with many constructor parameter…
Chapter 2 Creating and Destroying Objects item 1:Consider static factory methods instead of constructors 一个static factory method只不过是一个返回这个类的实例的static方法.与设计模式中的factory method是不同的概念.static factory methods有几点好处: 一.它们可以有自己的名字,而不像constructor只能与类名相同.一个好的名字…
第1章 引言 第2章 创建和销毁对象 第1条:考虑用静态工厂方法代替构造器(Consider static factory methods instead of constructors) 第2条:遇到多个构造器参数时要考虑用构建器(Consider a builder when faced with many constructor parameters ) 第3条:用私有构造器或者枚举类型强化Singleton属性( Enforce the singleton property with a…
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将近8年的时间,但随着Java 6,7,8,甚至9的发布,Java语言发生了深刻的变化. 在这里第一时间翻译成中文版.供大家学习分享之用. 4. 使用私有构造方法执行非实例化 偶尔你会想写一个类,它只是一组静态方法和静态属性. 这样的类获得了不好的名声,因为有些人滥用这些类而避免以面向对象方式思考,但是它们确实…