Java中的命名参数习语 [英] Named Parameter idiom in Java

查看:122
本文介绍了Java中的命名参数习语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中实现命名参数习语? (特别是对于构造函数)

How to implement Named Parameter idiom in Java? (especially for constructors)

我正在寻找类似于Objective-C的语法,而不是像JavaBeans中使用的语法。

I am looking for an Objective-C like syntax and not like the one used in JavaBeans.

一个小代码示例没问题。

A small code example would be fine.

谢谢。

推荐答案

我在构造函数中模拟关键字参数的最佳Java习惯是Builder模式,在有效的Java第二版

The best Java idiom I've seem for simulating keyword arguments in constructors is the Builder pattern, described in Effective Java 2nd Edition.

基本思想是让一个Builder类具有不同构造函数参数的setter(但通常不是getter) 。还有一个 build()方法。 Builder类通常是用于构建的类的(静态)嵌套类。外层类的构造函数通常是私有的。

The basic idea is to have a Builder class that has setters (but usually not getters) for the different constructor parameters. There's also a build() method. The Builder class is often a (static) nested class of the class that it's used to build. The outer class's constructor is often private.

最终结果如下所示:

public class Foo {
  public static class Builder {
    public Foo build() {
      return new Foo(this);
    }

    public Builder setSize(int size) {
      this.size = size;
      return this;
    }

    public Builder setColor(Color color) {
      this.color = color;
      return this;
    }

    public Builder setName(String name) {
      this.name = name;
      return this;
    }

    // you can set defaults for these here
    private int size;
    private Color color;
    private String name;
  }

  public static Builder builder() {
      return new Builder();
  }

  private Foo(Builder builder) {
    size = builder.size;
    color = builder.color;
    name = builder.name;
  }

  private final int size;
  private final Color color;
  private final String name;

  // The rest of Foo goes here...
}

要创建Foo的实例,您可以编写如下内容:

To create an instance of Foo you then write something like:

Foo foo = Foo.builder()
    .setColor(red)
    .setName("Fred")
    .setSize(42)
    .build();

主要警告是:


  1. 设置模式非常详细(如您所见)。可能不值得,除了你计划在很多地方实例化的类。

  2. 没有编译时检查所有参数都被指定了一次。您可以添加运行时检查,或者只能将其用于可选参数,并将所需参数的常规参数设置为Foo或Builder的构造函数。 (人们通常不担心多次设置相同参数的情况。)

您可能还想检查此博客文章(不是我) 。

You may also want to check out this blog post (not by me).

这篇关于Java中的命名参数习语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆