简体   繁体   中英

Android Java: Choose dynamically a subtype class

I have two classes (D and E) that have some common methods, the only difference is that D instantiates a singleton (A) and E instantiates another singleton(B).

E inherits from D and since the methods exec the same code, I' d like to check in D if I should create A or B singleton for not rewriting in E the same code of every common method...

A and B have inheritance from C abstract class...

Any advices?

Thanks in advance...

//Check subtype
if ....
  A field = A.getInstance().getMethod();
else...
  B field = B.getInstance().getMethod();

field.set...

I think the nicest solution would be to create an interface C and to make A and B implement this interface. Declare the methods you want to use in D and E in the interface, eg:

public interface C {
    public void setThatImportantField(String value);
}

In D , add a method that creates the singleton instance:

protected C createSingletonInstance() {
    return new A();
}

In E , override this method and return a new instance of B . In your initialization code in D , you now may use the methods defined in the interface:

protected void initSingleton() {
    C singleton = createSingletonInstance();
    singleton.setThatImportantField("test");
}

Best advice I can give: read good books on OO design.

More to the point, inheritance should only be used when the true relationship between the father and son is a "is a" relationship. Code reuse can be achieved in other ways (eg a utility class used by both).

You can create a method in D that only creates the singleton and use it. Implement it in one way in D and override it with another implementation in E.

创建单例参数的方法并只使用一个类(而不是D和E)来完成这项工作不起作用?

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