Builder-Muster vs. Konfigurationsobjekt

Das Builder-Muster ist beliebt, um unveränderliche Objekte zu erstellen. Das Erstellen eines Builders ist jedoch mit einem gewissen Programmieraufwand verbunden. Ich frage mich also, warum ich nicht einfach ein Konfigurationsobjekt verwende.

Die Verwendung eines Builders würde folgendermaßen aussehen:

Product p = Product.Builder.name("Vodka").alcohol(0.38).size(0.7).price(17.99).build();

s ist offensichtlich, dass dies sehr gut lesbar und prägnant ist, aber Sie müssen den Builder implementieren:

public class Product {

    public final String name;
    public final float alcohol;
    public final float size;
    public final float price;

    private Product(Builder builder) {
        this.name = builder.name;
        this.alcohol = builder.alcohol;
        this.size = builder.size;
        this.price = builder.price;
    }

    public static class Builder {

        private String name;
        private float alcohol;
        private float size;
        private float price;

        // mandatory
        public static Builder name(String name) {
            Builder b = new Builder();
            b.name = name;
            return b;
        }

        public Builder alcohol(float alcohol) {
            this.alcohol = alcohol;
            return.this;
        }

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

        public Builder price(float price) {
            this.price = price;
            return.this;
        }

        public Product build() {
            return new Product(this);
        }

    }

}

Meine Idee ist, den Code mithilfe eines einfachen Konfigurationsobjekts wie folgt zu reduzieren:

class ProductConfig {

        public String name;
        public float alcohol;
        public float size;
        public float price;

        // name is still mandatory
        public ProductConfig(String name) {
            this.name = name;
        }

}

public class Product {

    public final String name;
    public final float alcohol;
    public final float size;
    public final float price;

    public Product(ProductConfig config) {
        this.name = config.name;
        this.alcohol = config.alcohol;
        this.size = config.size;
        this.price = config.price;
    }

}

Verwendung

ProductConfig config = new ProductConfig("Vodka");
config.alcohol = 0.38;
config.size = 0.7;
config.price = 17.99;
Product p = new Product(config);

Diese Verwendung benötigt ein paar Zeilen mehr, ist aber auch sehr lesbar, aber die Implementierung ist viel einfacher und möglicherweise für jemanden, der mit dem Builder-Muster nicht vertraut ist, einfacher zu verstehen. Übrigens: Gibt es einen Namen für dieses Muster?

Gibt es einen Nachteil im Konfigurationsansatz, den ich übersehen habe?

Antworten auf die Frage(18)

Ihre Antwort auf die Frage