Tho*_*ler 8 java design-patterns
之前我曾与C#合作过,我考虑过了
Calendar cal = Calendar.getInstance();
Run Code Online (Sandbox Code Playgroud)
根据GoF Singleton模式(维基百科)成为单身方法,我想知道如何创建两个日历,因为Date有些不赞成.
从文档中
使用默认时区和区域设置获取日历.
和重载
getInstance(TimeZone zone)
getInstance(Locale aLocale)
Run Code Online (Sandbox Code Playgroud)
在我看来,这是对单例模式的概括,以便为每个时区和语言环境创建单例.但是我想在同一时区里有两个日历.
但是,当我进行测试时
@Test
public void test()
{
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
assertTrue(cal == cal2);
}
Run Code Online (Sandbox Code Playgroud)
它失败了,告诉我这个getInstance()方法实际上不是单例模式getInstance()方法,而是其他方法.
那么,一般来说,是否getInstance()根据Java中的单例模式表示单例?如果是这样,Java文档中的关键措辞是什么,以找出它是或不是单身?如果没有,我如何识别Java中的单例模式?或者是Calendar唯一的例外?
我不想在每次getInstance()接听电话时都进行单元测试.
我读过这个答案"在Java中实现单例模式的有效方法是什么?" ,这与C#完全相同,这与Calendar实现相矛盾.
Calendar不是单例,每次调用都Calendar.getInstance(...)返回一个不同的实例.Javadoc没有说每个调用都会返回相同的实例,所以你没有理由认为它会.
Calendar.getInstance(...) 更符合工厂设计模式.
查看其他示例getInstance,例如Locale.getInstance(),您会看到Javadoc告诉您连续调用是否可能返回相同的实例:
/**
* Returns a <code>Locale</code> constructed from the given
* <code>language</code>, <code>country</code> and
* <code>variant</code>. If the same <code>Locale</code> instance
* is available in the cache, then that instance is
* returned. Otherwise, a new <code>Locale</code> instance is
* created and cached.
*
* @param language lowercase two-letter ISO-639 code.
* @param country uppercase two-letter ISO-3166 code.
* @param variant vendor and browser specific code. See class description.
* @return the <code>Locale</code> instance requested
* @exception NullPointerException if any argument is null.
*/
static Locale getInstance(String language, String country, String variant)
Run Code Online (Sandbox Code Playgroud)
同样,这不是单例,但实例是缓存的,正如Javadoc所说.除非Javadoc这样说,否则您可以期望每次调用getInstance都返回一个不同的实例.
| 归档时间: |
|
| 查看次数: |
4504 次 |
| 最近记录: |