How to make sure a class only can generate one object?

How to make sure a class only can generate one object?
First, let’s think about this:
———-D.java————-
package ch.allenstudy.newway02;
public class D
{
}
class A
{
}
class C
{
public int i = 10; //i 是 C 的属性
}
————————-
这个没有问题吧, i 是 C 的属性。
Let’s add one more line:
———-D.java————-
package ch.allenstudy.newway02;
public class D
{
}
class A
{
}
class C
{
public int i = 10; //i 是类 C 的属性
public A a = new A(); //a 是否是类 C 的属性呢?
}
————————-
Is “a” the property of class C?
Answer is Yes.
“a” is the property of class C, just that its type is: A
a 也是 C 类的属性,只不过他不是普通的 int string 等型,是一个 C 类型的。
继续增加代码。
———-D.java————-
package ch.allenstudy.newway02;
public class D
{
public static void main(String[] args)
{
C cc = new C();
cc.g();
}
}
class A
{
public void f()
{
System.out.printf(“Ha ha!\n”);
}
}
class C
{
public int i = 10; //i 是 C 的属性
public A a = new A(); //a 是 C 的属性,类型为 A
public void g()
{
a.f();
}
}
———Result——–
Ha ha!
其实上面讲的是一个包含关系,类 C 其实包含了类 A 的一个对象 a。
就好比汽车这个类,包含了发动机这个类的对象一样,把它作为了自己的一个属性。

那么,同理,一个类,也可以把自身的对象作为自己的属性。 For example:
———-D.java————-
package ch.allenstudy.newway02;
public class D
{
public static void main(String[] args)
{
}
}
class A
{
public int i = 20;
A aa = new A(); //now, aa is A’s property. And at same time, it’s an object.

private A()
{
}
}

Now, let’s back to the topic of the post: How to make sure a class only can generate one object?
Look at below code block.
———-D.java————-
package ch.allenstudy.newway02;
public class D
{
public static void main(String[] args)
{
A aa1 = A.getA(); // 将返回的 aa 对象赋给 aa1
A aa2 = A.getA(); // 将返回的 aa 对象赋给 aa2
aa1.i = 99; //set aa1.i to 99.
System.out.println(aa2.i); //Print aa2.i. If it’s still 20, means aa1 and aa 2 are different objects; if it’s 99, means they are the same object, so only can create one object.
if (aa1 == aa2)
System.out.println(“Yes, aa1 equals aa2″); //judge whether they are same.
}
}
class A
{
public int i = 20;
public static A aa = new A(); // use an object as property; in fact it’s a pointer point to itself. Also, here must be “static”, otherwise, static method getA() can’t access dynamic property.

private A() //Notice: here, the constructor A() is private, so you are not able to new A().
{
}

public static A getA() //here must be “static”, otherwise you can’t call it
{
return aa; //return an A object.
}
}
——–result——–
99
Yes, aa1 equals aa2
———————-

posted @ 2011-12-02 07:40  allenbackpacker  阅读(110)  评论(0编辑  收藏  举报