简体   繁体   English

支持同一 class 的多个版本的优雅方式?

[英]An elegant way to support multiple versions of the same class?

I have the following code:我有以下代码:

MyVersion6 myClass = returnMyClass();

// about 50 lines of code that do the following:
// do some logic with fields of myClass
// create and return another class using some fields of myClass

Now I have to support version 7 and I can return it in the returnMyClass() method.现在我必须支持版本 7,我可以在 returnMyClass() 方法中返回它。

What's the most elegant way to implement the remaining 50 lines?实现剩余 50 行的最优雅方式是什么? In this case, MyVersion6 and MyVersion7 support exactly the same methods but I don't want to do it like在这种情况下,MyVersion6 和 MyVersion7 支持完全相同的方法,但我不想这样做

if ( myClass instanceOf MyVersion6 )
      do the 50 lines using (MyVersion6) myClass 
else if ( ( myClass instanceOf MyVersion7 )
      do the exact same 50 lines using (MyVersion7) myClass 

Any ideas?有任何想法吗?

I suggest you to create a interface that will be implemented by classes like MyVersion6 MyVersion7我建议您创建一个接口,该接口将由MyVersion6 MyVersion7等类实现

Example例子

public class MyVersion7 implements someInterface{}
public class MyVersion6 implements someInterface{}

Then you can check然后你可以检查

if ( myClass instanceOf someInterface)
      do the 50 lines using (someInterface) myClass 

instanceOf someInterface will yield true if any class has implemeneted that interface.如果任何 class 已实现该接口,instanceOf someInterface 将产生 true。

The new version object should avoid changing the interface (API).新版本 object 应避免更改接口(API)。 Since new versions share a lot of common code with the original version, I would use inheritance and let dynamic dispatch handle the difference.由于新版本与原始版本共享许多通用代码,我将使用 inheritance 并让动态调度处理差异。 I would then only use casting in the case of a new version that has a specific method.然后,我只会在具有特定方法的新版本的情况下使用强制转换。 But you should avoid adding specific methods to new versions.但是您应该避免将特定方法添加到新版本中。

class MyObject {
    public String toString() { return "MyObject"; }
}

class MyObjectV2 extends MyObject {
    public String toString() { return "MyObjectV2"; }
}

class MyObjectV3 extends MyObjectV2 {
    public String toString() { return "MyObjectV2"; }
    public void v3specific() { System.out.println("v3 specific method");}
}

public class JavaApplication24 {

    public static void main(String[] args) {
        MyObject[] objects = {new MyObject(), new MyObjectV2(), new MyObjectV3()};
        for (MyObject o : objects) {
            System.out.println(o);
            if (o instanceof MyObjectV3)
                ((MyObjectV3)o).v3specific();  
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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