公共静态工厂方法 [英] public static factory method

查看:77
本文介绍了公共静态工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,如果这是一个愚蠢的问题,请原谅我,我只是在尝试学习这种语言的核心.我正在阅读《有效的Java》,第一章讨论了静态工厂方法与构造方法.他们的利弊.令我困惑的几件事是:

First of all please forgive me if its a really dumb question, I am just trying to learn this language to its core. I am reading Effective Java and the very first chapter talks about Static factory methods vs. Constructors. Their pros and cons. Few things that are confusing to me are:

    静态工厂方法返回的对象的
  1. 类是非公开的-究竟是什么意思?
  2. 与构造函数不同,每次调用新工厂都不需要使用静态工厂方法-这种情况如何发生?我仅使用工厂方法来获取新对象,我们是否将检查方法放入工厂方法中以检查对象是否已存在?
  1. class of an object returned by static factory method is nonpublic - what exactly does it mean?
  2. unlike constructors static factory methods are not required to create a new object each time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?

谢谢.

推荐答案

静态工厂方法返回的对象的

类是非公共的- 到底是什么意思?

class of an object returned by static factory method is nonpublic - what exactly does it mean?

这意味着静态工厂方法返回的对象的实际类可以是声明类型的子类,并且此子类不必是公共的.这只是客户端代码不关心的另一个实现细节.

It means that the actual class of the objects returned by a static factory method can be a subclass of the declared type, and this subclass does not have to be public. It's just another implementation detail that client code should not care about.

与构造函数不同,每次调用新工厂时,都不需要静态工厂方法来创建新对象-这是怎么发生的?我仅调用工厂方法来获取新对象,是否将检查方法放入工厂方法中以检查对象是否已存在?

unlike constructors static factory methods are not required to create a new object each > time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?

是的,这是可以完成此操作的一种方式.但实际上,一切皆有可能.

Yes, that's one way this could be done. But really, anything is possible.

这篇关于公共静态工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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