Java 的 Builder 模式生成器 FreeBuilder

码农软件 · 软件分类 · Java开发工具 · 2019-11-06 18:12:31

软件介绍

FreeBuilder

为 Java 1.6+ 自动生成 Builder 模式

当设计类的构造函数或静态工厂具有多个参数时,Builder 模式是一个不错的选择。—— Effective Java,第二版,第39页

背景

在 Java 中实现 Builder 模式容易出错和重复。即使是一个简单的四字段类,最基本的构建器 API 需要 39 行代码,如果你不使用像 AutoValue 这样的实用程序来生成值样板,则需要 72 行代码。

使用

import org.inferred.freebuilder.FreeBuilder;

@FreeBuilder
public interface Person {
  /** Returns the person's full (English) name. */
  String name();
  /** Returns the person's age in years, rounded down. */
  int age();
  /** Builder of {@link Person} instances. */
  class Builder extends Person_Builder { }
}

JavaBean convention

如果值类型遵循 JavaBean 命名约定,只需在访问器方法前面加上'get'(或者,布尔访问器是'is')。 FreeBuilder 会跟随,并在 setter 方法上添加“set”前缀,以及从 toString 输出中删除前缀。

@FreeBuilder
public interface Person {
  /** Returns the person's full (English) name. */
  String getName();
  /** Returns the person's age in years, rounded down. */
  int getAge();
  /** Builder of {@link Person} instances. */
  class Builder extends Person_Builder { }
}

Person person = new Person.Builder()
    .setName("Phil")
    .setAge(31)
    .build();
System.out.println(person);  // Person{name=Phil, age=31}

本文地址:https://codercto.com/soft/d/18413.html

Writing Apache Modules with Perl and C

Writing Apache Modules with Perl and C

Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95

Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具