0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Consumer interfaceを使用してconstructorの引数追加の影響を減らす

Last updated at Posted at 2023-01-12

constructor使わずbuilderでinstance生成する
builderにItemと同じフィールドを持たせる
builderに値設定するロジックをconsumerとして引き渡す
builder内部でconsumer実行
builder内容でItemを生成するコンストラクタ実行

class Item {
    private int price;
    private String name;
    public Item() {}
    private Item(Builder build) {
        this.price = build.price;
        this.name = build.name;
    }
    public String toString() {
        return "name:" + name + " price:" + price;
    }
    
    static class Builder {
        int price;
        String name;
        
        Builder method(Consumer<Builder> c) {
            c.accept(this);
            return this;
        }
        Item build() {
            return new Item(this);
        }
    }
}
public class Outer {
    public static void main(String[] args) {
        Item i = new Item.Builder().method(b -> {b.name = "suzuki"; b.price = 90;}).build();
        System.out.println(i);
    }
}
name:suzuki price:90
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?