简体   繁体   中英

List<Object> abcList and method overloading

I am wondering if there is a short cut for my current problem.

I have a List abcList.

It contains 3 type of objects/Entity ABC (they did not inherit a common interface or parent, with exception to Object>.

They are hibernate Entity.

I have 3 overloaded method.

process(A a)
process(B b)
process(B C)

I was hoping to loop the

List abcList and just calling process();

for(Object o: abcList) process(o);

is there an easy solution for my current problem? I am implementing a class that contain 3 different type of object List.

As the binding is at compile time, it's impossible to know. If you can add an interface to those classes, you can use the Visitor pattern.

In addition to the visitor pattern, another thing to consider is putting a layer of indirection in when adding to the list. Instead of putting the object in directly, put in an object that can process that has references to both the object and the outer context.

This is a good place for using the visitor pattern . Without resorting to reflection, you'll need to define a common interface for the objects in your List. Let's start there:

interface Visitable {
    void accept(Visitor v);
}

The Visitor, then, is where you define the process methods for each concrete type:

interface Visitor {
    void process(A a);
    void process(B b);
    void process(C c);
}

Now, a concrete Visitable is able to invoke the proper overloading of process() since it is, of course, aware of it's own concrete type at compile time. For example:

class A implements Visitable {
    void accept(Visitor v) {
        v.process(this);
    }
}

Classes B and C will do the same. So now you end up with your processing loop:

List<Visitable> abcList = ...;
Visitor visitor = ...;

for (Visitable o : abcList) {
    o.accept(visitor);
}

Again, if you are not able to define a common interface for all your classes then you can still achieve this with the Visitor Pattern using Reflection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM