English 中文(简体)
Java成员同一类的物体
原标题:Java member object inside class of same type
  • 时间:2010-07-01 14:06:43
  •  标签:
  • java
  • oop

我正在研究一个法典基础,我经常看到这样的情况:

public class SomeClass
{
 protected static SomeClass myObject;

 //...

 public static SomeClass getObject()
 {
  return myOjbect
 }
}

I d like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I d search for the answer, so if this pattern has a name, please let me know.

而且,这似乎只是鸡肉和鸡蛋的定义,因为该类含有该类的物体。 为什么这种说法实际上自相矛盾?

感谢!

最佳回答

这确实与Singleton patterns完全相同,只有这一类的一个例子。 虽然单一州有其用途,但经常被滥用(通常是将程序方案拟订伪装成业务处)。 Java AWT或Swaing的典型代码也经常出现这种情况,其中通常为Frame/JFrame,并在main上树立了一个榜样。 同一类别内的方法。

Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn t this actually paradoxical?

为什么你们认为是? 该类别主要描述这类成员instances,但static 成员不属于某一例,属于该类成员,因此与该类“蓝印”作用没有任何关系。 由于这一点,法定成员实际上有些是非办事处。

但是,即便在例一级,你也可以有同样的提法。 例如,链接名单上的条目通常有两处提及下两个条目和以前的条目,这两个条目相同。

问题回答

这称为Singleton设计模式。

你正确地指出,目的是确保只设立一间教室。

Wikipedia 在该模式上有一个良好的条款。

你提到的模式被称为“Singleton”,但从你的法典样本来看,这还不清楚,这是否真正是打算的。 由于该成员受到保护,我不认为——如果是分级,则可能不会有单一情况。

它称作单一州。 你们确保只创造一(1)个特定类别的物体。

您应加上一名私人司机,因此,唯一制造物体的人就是这一类别。

public class SomeClass
{
 // Using private constructor
 protected static SomeClass myObject = new SomeClass();

 private SomeClass(){
 //...
 }

 public static SomeClass getObject()
 {
  return myOjbect
 }
}

http://en.wikipedia.org/wiki/Singleton_pattern”rel=“nofollow noreferer”>Wikipedia

http://en.wikipedia.org/wiki/Factory_method_pattern” rel=“nofollow noretinger”>Factory Format





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签