Creating an object based on the state of another object in Java

Suppose you have a class called Explosion where it makes no sense to instantiate it without any information from another instance of the class. The constructor is not published.

Is it better to do this:

// both classes are in the same package  
Explosion e;  
Collision c = new Collision()    
// do some stuff with collision  
e = c.createExplosion()

Or better, if Explosion has a static method to instantiate, and you pass the Collision object as an argument:

Explosion e  
Collision c = new Collision()    
// do some stuff with collision  
e = Explosion.createExplosion(c)

When you are the author of both classes.

+5
source share
7 answers

Why is the constructor not publicly available? It would seem reasonable to me that Explosion have a constructor that references the Collision link as a parameter.

So you could:

Explosion e;
Collision c = new Collision();
// do some stuff with collision
e = new Explosion(c);
+4
source

, . , , , . factory, , - Explosion, .

? , ?

+3

... .

Explosion Collision, () . ​​ (, , ). , , Explosion, Collision.

, , Collision Explosion, . . , - , Explosion Collision.

+3

, , , OO.

+1

. " ", , "" .

: -, : , , ( )? .. .

, (, ), , ?

"", , . , , , .

+1
+1

The advantage of the second approach is that you do not need to create an Explosion object each time (referring to Effective Java ). If you want to have some kind of caching mechanism (say, you want to return the same Explosion instance based on some attributes of the Collision class), then the second approach will be useful.

On the other hand, if the Explosion class provides only a static factory method for instantiating, then it cannot be a subclass.

+1
source

All Articles