问题描述:

So I know that reference variables cannot be changed.

I'm in a position where I have two different classes. Let's call them A and B. They have the same methods (the methods are called the same) they're just specified for the class.

I need a clever way of changing between which classes to instantiate.

One way could be with some boolean tests checking which option has been selected and then instantiate the corresponding class. Although I fear that this might become bulky and ugly, so I'm trying to avoid this way. There must be something more clever.

Currently I'm thinking of making a new class (e.g. C) that extends the same class as A and B.

I would then override the methods (as class A and B also do btw) and then execute the methods depending on the setting (i.e. which class A or B is selected). The methods would return the same as it would in class A or B.

Hope I'm not talking complete gibberish.

网友答案:

One way to do this is to use the Factory Pattern.

Partial quote from Wikipedia:

Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created.

E.g.

public abstract class Base {

    public abstract void doSomething();
}

public class A extends Base {

    public void doSomething() {
        System.out.println("A");
    }
}

public class B extends Base {

    public void doSomething() {
        System.out.println("B");
    }
}

public class C extends Base {

    public void doSomething() {
        System.out.println("C");
    }
}

public interface BaseFactory {

    public Base createBase(int condition);

}

public class DefaultBaseFactory implements BaseFactory {

    public Base createBase(int condition) {

        switch (condition) {
            case 0 : return new A();
                break;

            case 1: return new B();
                break;

            case 3: return new C();
                break;

            default: return null;
                break;
        }
    }
}
网友答案:

Your explanation is confusing. But it sounds like you should extend A and B from a common base class (or an interface):

abstract class Base {
    public abstract void someMethod();
}

class A extends Base {
    public void someMethod() { System.out.println("A"); }
}

class B extends Base {
    public void someMethod() { System.out.println("B"); }
}

That means you can do something like this:

Base base;
if (someCondition) {
    base = new A();
}
else {
    base = new B();
}

base.someMethod();
相关阅读:
Top