Several operations depending on the type of the passed object
Assuming I am creating a method that is passed to an object and that method will take action based on the passed object. How to identify an object?
I thought about using the class name to identify the object, but that might not be practical as I could easily change the class name of the objects and generate headaches during future development. I'm right?
edit: for example i have ball and bomb objects. if I have another object called a wall, and the wall has a way to resolve collisions with the wall (for example, the coordinates of the colliding ball and bomb), but has different logic depending on the colliding object (i.e., the ball and bomb)
a source to share
What you are asking for is an operator instanceof
.
if (object instanceof SomeClass) {
// do something
} else if (object instanceof SomeOtherClass) {
// do something else
}
However, this is not a good practice. Instead, you can use what's called double dispatch. Make the passed object compatible with an interface that defines an operation in terms of another class. So:
public interface ThrowableItem {
void throwAt(Wall wall);
}
public class Wall {
void accept(ThrowableItem item) {
item.throwAt(this);
}
}
And then list the appropriate implementations in Ball
and Bomb
(both of which implement ThrowableItem
)
Take a look at the Visitor Template - you can move operations to WallVisitor
, which knows how to handle collisions for each object.
a source to share
It depends on what actions are there. How are they related? Do you have multiple objects that do the same thing, but in a slightly different way? For example, suppose I have a method that needs to print a document, but I want the same method to print PDF and doc files.
If your situation is similar to your situation, you can consider using inheritance like this: Create a superclass, in my example, you can call it Document using the print () method. The printing method doesn't have to do anything. Then subclass each document type so that I end up with a subclass of PdfDocument and DocDocument. Each of these will provide an implementation for print () that can print the type of document it belongs to.
Then the method I am writing would be:
public void printDocument(Document d){
d.print();
}
That is, by specifying the type of the superclass, I don't have to worry about the specific action that each document type does. This way I avoid code that checks the type of the object that is passed to my method. This makes the code more robust for future extensions.
a source to share