java方法可以根据条件返回值吗?

时间:2015-06-03 07:02:23

标签: java design-patterns

我有ICoreClient接口,AClientBClient类实现此功能。

用户可以使用

ICoreClient

我需要在ICoreClient界面中添加新方法。因此,它需要在两个客户端中实现。我不能使这种方法通用,因为它具有完全不同的签名但功能相似。

我有2个接口xxyy

ClientA实施xxClientB实施yy

所以,我决定在testMethod中添加一个新的ICoreClient,它会根据客户提供xxyy的实例。

我想根据条件从单个方法返回这些接口的实例。

ClientA

public xx testMethod(){
  return instanceof xx;
}

ClientB

public yy testMethod(){
  return instanceof yy;
}

我应该在ICoreClient界面写什么?

public zz testMethod()

我尝试使用虚拟接口 zz(充当常见的超类型)xxyy正在实现这一点。但是仍然无法在各自的客户端中公开xxyy的方法,因为它最终在zz进行了类型转换。

这种情况有没有已知的方法?

编辑:如果我返回类型Object,则不会公开这些接口的方法。虽然,Object包含xxyy

的实例

用户仍需要将其转换为(xxyy用户将如何知道?)以使用界面中的方法..我想公开ClientX的方法无需转换为ClientAClientB ...

3 个答案:

答案 0 :(得分:38)

编辑后,您可能正在寻找generics。你可以像这样建立你的界面

interface ICoreClient<T>{// T will be set by each class implementing this interface
    T testMethod();
}

并且每个类看起来都像

class ClientA implements ICoreClient<xx>{
    xx testMethod(){
        //return xx
    }
}

class ClientB implements ICoreClient<yy>{
    yy testMethod(){
        //return yy
    }
}

答案 1 :(得分:16)

只有当xxyy具有共同的超类型(接口或类)时才有可能。在最坏的情况下,您始终可以返回Object。

public Object testMethod () // or a more specific common super type of `xx` and `yy`
{    
    if (..some condition..) {
        return ..instanceof `xx`..;
    } else if (..other condition..) {
        return ..instanceof `yy`..;
    }
    return null; // or some other default instnace
}

答案 2 :(得分:0)

作为返回对象意味着您必须在客户端进行转换,您可以返回包含可能值的自定义对象:

public class MethodResult
{
    private xxx xResult;
    private yyy yResult;
    public MethodResult(xxx xResult){
        this.xResult=xResult;
    }
    public MethodResult(yyy Result){
        this.yResult=yResult;
    }
    public xxx getXResult(){return xResult;}
    public yyy getYResult(){return yResult;}
}

然后返回此类型:

public MethodResult testMethod () 
{
    if (..some condition..) {
            return new MethodResult(new xxx());
        } else if (..other condition..) {
            return new MethodResult(new yyy());;
        }
    }
}

然后客户端可以检查哪个结果不为null并相应地使用该类型,可以访问xxx或yyy上定义的所有方法,具体取决于设置的方法。或者你可以添加一个方法,它允许你检查设置的结果做出决定,而不是检查null ......