抽象类 NumberFormat - 对 getInstance() 非常困惑 [英] abstract class NumberFormat - very confused about getInstance()
本文介绍了抽象类 NumberFormat - 对 getInstance() 非常困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java 新手,我有一个初学者问题:
I'm new to Java and I have a beginner question:
NumberFormat
是一个抽象类,所以我假设我无法创建它的实例.但是有一个公共静态(工厂?)方法 getInstance()
允许我做
NumberFormat
is an abstract class and so I assume I can't make an instance of it. But there is a public static (factory?) method getInstance()
that allow me to do
NumberFormat nf = NumberFormat.getInstance();
我很困惑.如果有人能给我提示,我会很高兴:
I'm quite confuse. I'll be glad if someone could give me hints on:
- 如果有一个公共方法来获取这个抽象类的一个实例,为什么我们没有一个构造函数呢?
- 这是一个抽象类;我们如何让这个静态方法给我们一个类的实例?
- 为什么选择这样的设计?如果我假设有可能有一个抽象类的实例 (???),我就不明白为什么这个类应该是抽象的.
谢谢.
推荐答案
- 该类是抽象类,因为它是 Java 中每种数字格式的基类(例如,这包括
DecimalFormat
).拥有一个基本未知的数字格式的构造函数是非常无用的. getInstance()
方法是所谓的工厂方法.它返回当前语言环境的匹配数字格式.由于不知道在编译时需要什么样的子类,它返回一个NumberFormat
,但是,实例 本身将是一个子类型,显然(因为你不能创建抽象类的实例).- 这种设计使您可以以某种方式灵活地确定在运行时返回的正确子类实例,而不会在设计/编译时使该设计过于僵化.静态方法免于抽象,因此类可以作为工厂和具体实现的抽象超类型.如果不是这种情况,您可能会有一个
NumberFormatFactory
某处有工厂方法.
- The class is abstract because it is the base class for every number format in Java (this includes
DecimalFormat
, for example). Having a constructor for an essentially unknown number format is pretty useless. - The
getInstance()
method is a so-called factory method. It returns a matching number format for the current locale. Since it is not known what kind of sub-class is required at compile-time, it returns aNumberFormat
, however, the instance itself, will be of a sub-type, obviously (since you can't create instances of abstract classes). - This design gives you the flexibility of somehow determining the proper subclass instance to return at runtime without making too much of that design rigid at design/compile time. Static methods are exempt from being abstract so a class can work as both a factory and an abstract supertype for concrete implementations. If this weren't the case you'd probably have a
NumberFormatFactory
somewhere which would have the factory methods.
这篇关于抽象类 NumberFormat - 对 getInstance() 非常困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文