Java 构建器模式实现与 C#

Java Builder pattern implementation versus C#

我来自 .NET 世界,但现在我正在看一本书,其中所有示例都是用 Java 编写的。这是代码片段:

public class Order {
    static class Builder {
        private String security;
        private int quantity;

        public Builder() {}

        public Builder buy(int quantity, String security) {
            this.security = security;
            this.quantity = quantity;
        }

        // some other builder pattern methods...

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

    private final String security;
    private final int quantity;

    private Order(Builder b) {
        security = b.security;
        quantity = b.quantity;
    }
}

因此,如果有人可以向我解释: 1. 我们如何让静态 class 具有非静态字段? 2. 这本书的作者是这样写的: 通过将构建器用作可变对象,您可以确保 Order 数据成员的不变性,以便于 concurrency.

谁能给我一个例子,它如何在我们仍然有可变构建器对象时真正简化并发问题,这将有相同的并发问题,就像我们有可变 Order 一样。

Q: How can we have static class with non-static fields?

static 修饰符在 C# 和 Java 中的含义不同。

在 C# 中,这意味着 class 不能实例化或子classed。它基本上使 class 成为 static 成员的容器。

在 Java 中,class 上的 static 修饰符意味着它不会隐式引用外部 class.[=20 的实例=]

Docs:

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Q: The author of the book is writing such thing: By using the builders as the mutable object, you ensure the immutability of the Order data members for easier concurrency.

构建器是可变的,但构建的实际对象是不可变的(在 C# 中,它的所有字段都是 final == readonly)。

当一个对象不可变时,它本质上是线程安全的:您可以在多个线程中同时使用它而无需锁定,因为它保证所有这些线程只会对该对象执行读取。不需要同步意味着更容易并发。