简体   繁体   English

Java并发性主题:对象或其内部状态的发布

[英]Java concurrency topic: publication of objects or its internal state

I'm reading the code base of a project, and here's some code I can't under stand: 我正在阅读项目的代码库,下面是一些我无法理解的代码:

protected BaseApiCommand(String apiName, ApiParams params, boolean isGetRequest) {
    this.apiName = apiName;
    this.apiParams = params;
    this.isGet = isGetRequest;
    if (apiParams == null) {
        apiParams = new ApiParams();
    }
}

public static BaseApiCommand createCommand(String apiName, boolean isGet, ApiParams params) {
    return new BaseApiCommand(apiName, params, isGet);
}

I know it's about publication, but I just can't understand why it's unsafe otherwise to expose the constructor directly. 我知道这是关于发布的,但是我只是不明白为什么直接公开构造函数是不安全的。 Can anyone explain it in detail ? 谁能详细解释一下?

In fact the static function is a static factory method to the class, as proposed by Joshua Bloch in Effective Java. 实际上,正如Joshua Bloch在Effective Java中所提出的那样,静态函数是该类的静态工厂方法。 This is a very common pattern in Java language and protects the constructor from the class consumers. 这是Java语言中非常常见的模式,可保护构造函数免受类使用者的侵害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM