【问题标题】:how to write a true default method to avoid code duplication如何编写真正的默认方法以避免代码重复
【发布时间】:2018-06-04 11:32:44
【问题描述】:

我想编写两个类实现带有参数的默认方法的接口 - 函数名称并在两个类中使用它,但不知道如何将方法名称作为参数。必须避免重复。

interface C {
        default public StatusEntry getServiceStatus(){????}
}

class A implements C { 

    private StatucBType getSatusA(){...} 

    @Override
    public StatusEntry getServiceStatus() throws Exception {
        StatusEntry result = new StatusEntry();
        ServiceStatus status;
        try {
            status = **getSatusA()**/*need make as a parametr*/.getStatus();
        } catch (Exception e) {
        }
        result.Status(status);
        return result;
    }
}

class B implements C {    
    private StatucBType getSatusB(){...}

    @Override
    public StatusEntry getServiceStatus() throws Exception {
        StatusEntry result = new StatusEntry();
        ServiceStatus status;
        try {
            status = **getSatusB()**/*need make as a parametr*/.getStatus();
        } catch (Exception e) {
        }
        result.Status(status);
        return result;
    }
}

【问题讨论】:

  • parameter 应该是什么?
  • 什么是默认方法,在那里我可以看到 public 和 privet 方法
  • “getSatusA()”或“getSatusB()”

标签: java oop inheritance interface


【解决方案1】:

如果您在接口中为方法getServiceStatus 添加参数,则具体实现也必须添加此参数,而且更重要的是,该方法的调用者必须知道要提供什么参数。

所以首先,不要给那个接口添加参数(至少,在这个小场景中是没有必要的)!

为避免代码重复,您可以添加一个托管代码的中间抽象类:

abstract class Z {

    final StatusEntry getServiceStatus(Supplier<StatucBType> statusProvider) throws Exception {
        StatusEntry result = new StatusEntry();
        ServiceStatus status;
        try {
            status = statusProvider.get().getStatus();
        } catch (Exception e) {
        }
        result.Status(status);
        return result;
    }

}

然后按如下方式使用:

class A implements C extends Z { 

    private StatucBType getSatusA() {...} 

    @Override
    public StatusEntry getServiceStatus() throws Exception {
        return getServiceStatus(this::getStatusA);
    }

}

【讨论】:

  • 好的,但是如果我有两个不同的类返回 getSatusA -> StatusAType 和 getSatusB -> StatusBType。 StatusAType 和 StatusBType 没有通用接口和抽象类,我可以使用 Supplier 吗?
  • ... 或常见的超类型。
【解决方案2】:

也许您正在寻找template method pattern

您的界面应该只有一个getStatus 方法,

StatucBType getStatus();

getServiceStatus 方法将是 default 并像这样实现:

default StatusEntry getServiceStatus() throws Exception {
    StatusEntry result = new StatusEntry();
    ServiceStatus status;
    try {
        status = getStatus().getStatus();
    } catch (Exception e) {
    }
    result.Status(status);
    return result;
}

现在你需要在AB中实现getStatus

// in A
public StatucBType getStatus { /*put the implementation of getStatusA here*/}
// in B
public StatucBType getStatus { /*put the implementation of getStatusB here*/}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 2012-05-02
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多