Java高效编程(2) -- Creating and Destroying Objects

Item 1: Consider static factory methods instead of constructors

Advantage:

One advantage of static factory methods is that, unlike constructors, they have names.

A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.

A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.

A fourth advantage of static factory methods is that they reduce the verbosity(冗长) of creating parameterized type instances.

Disadvantage:

The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.

A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.

Item 2: Consider a builder when faced with many constructor parameters

the telescoping constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it.

a JavaBean may be in an inconsistent state partway through its construction.

the JavaBeans pattern precludes the possibility of making a class immutable.

Advantage:

The Builder pattern simulates named optional parameters.

Class.newInstance breaks compile-time exception checking.

the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

Item 3: Enforce the singleton property with a private constructor or an enum type

Making a class a singleton can make it difficult to test its clients.

a single-element enum type is the best way to implement a singleton.

#1. Singleton with public final field

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

#2. 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() { ... }
}

#3. readResolve method to preserve singleton property

private Object readResolve() {
    // Return the one true Elvis and let the garbage collector
    // take care of the Elvis impersonator.
    return INSTANCE;
}

#4. Enum singleton - the preferred approach

public enum Elvis {
    INSTANCE;
    public void leaveTheBuilding() { ... }
}

Item 4: Enforce noninstantiability with a private constructor

Attempting to enforce noninstantiability by making a class abstract does not work.

a class can be made noninstantiable by including a private constructor.

public class UtilityClass {
    // Suppress default constructor for noninstantiability
    private UtilityClass() {
        throw new AssertionError();
    }
    ... // Remainder omitted
}    
时间: 2024-08-08 22:06:18

Java高效编程(2) -- Creating and Destroying Objects的相关文章

Effective Java P2 Creating and Destroying Objects

This chapter concerns creating and destorying objects : when and how to create them, when and how to avoid creating them, how to ensure they are destoryed in a timely manner, how to manage any cleanup actions that must precede their destruction. 原文地址

高效 告别996,开启java高效编程之门 3-2传统方式处理业务逻辑

1 重点 1.1 对sort方法使用的理解 2 代码演练 需求: 根据第一章需求,女盆友提出需求* 1 打印所有商品* 2 图书类的商品一定给买* 3 最贵的买两件* 4 打印最贵的两件商品的名称和总价 测试类: package com.imooc.zhangxiaoxi.stream; import com.alibaba.fastjson.JSON; import com.imooc.zhangxiaoxi.lambda.cart.CartService; import com.imooc.

高效 告别996,开启java高效编程之门 3-7实战:常用中间操作演示之:过滤/映射/扁平化 filter/map/flagMap

1 重点 filter方法的使用 map方法的使用 flatMap方法的使用 forEach方法的使用 2 map和flatMap的区别: map的作用很容易理解就是对rdd之中的元素进行逐一进行函数操作映射为另外一个rdd. flatMap的操作是将函数应用于rdd之中的每一个元素,将返回的迭代器的所有内容构成新的rdd.通常用来切分单词,可用来单词计数 3 实战演示之过滤(filter): package com.imooc.zhangxiaoxi.stream; import com.al

2. creating and destroying objects

ref: book "Effective Java" 1. consider static factory methods instead of constructord 2. consider a builder when faced with many constructor parameters 3. enforce the singleton property with a private constructor or an enum type 4. enforce nonin

高效 告别996,开启java高效编程之门 2-8实战:判断逻辑参数化-Lambda表达式

0 有用部分 1    函数式编程简介 2    函数式编程和lambda的关系 3    lambda表达式应用范围 4    lambda应用的五个案例 5    函数式编程应用条件 6 提出问题 0 有用部分 4 lambda应用的五个案例 5 函数式编程应用条件 6 提出问题 本节主要介绍了lambda的使用方式,具体demo参照2-10 和2-15 1 函数式编程简介 函数式编程是一种不同的编程思想,定义函数作为公民,可以赋值给变量,作为参数或者返回值来传递 2 函数式编程和lambd

Java高效编程(20) - 注解

built-in annotations, defined in java.lang:@Override@Deprecated@SuppressWarnings The meta-annotations are for annotating annotations: @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Test {} ///:~

高效 告别996,开启java高效编程之门 2-10实战:自定义函数式接口

1 有用部分 2    代码演练 1 有用部分 个人理解: 1.1 关于lambda的应用 通过 @FunctionalInterface注解 将其参数 fileContent  注入,调用的时候可以直接调取到. 服务层通过直接调用接口的方法,没有用实现类 1.2 关于文件流的读取操作 demo中设计更多的流的读取的操作 2 代码演练 需求: 将本地文件打印出来 接口: package com.imooc.zhangxiaoxi.lambda.file; /** * 接口中只有一个抽象方法,可以

高效 告别996,开启java高效编程之门 2-15方法引用精讲

2-14课程和2-12重复了,所以没有发出来 1 方法引用使用条件 判断方法引用 是否满足场景的要求的时候,只需要看我们的出参和入参是否满足接口的要求即可 2 方法引用场景 四种方法引用类型: 指向静态方法 Class::staticMethod指向现有对象的实例方法 object::instanceMethod指向任意类型的实例方法 C1ass::instanceMethod指向构造方法 Class::new 3 方法引用demo package com.imooc.zhangxiaoxi.l

高效 告别996,开启java高效编程之门 3-6流操作分类

1 重点 理解流程操作分类 常用的方法 2 Stream流操作分类: 2.1 流操作分类之中间操作(Intermediate): 无状态操作——filter/map/peek等有状态操作——dictinct/sorted/limit等 2.2 流操作分类之终端操作(Termina1):非短路操作——forEach/collect/count等短路操作——anyMatch/findFirst/findAny等 2.3 有状态操作无状态操作区别: 无状态操作: 比如map或者filter会从输入流中