如何编写一个真正的默认方法来避免代码重复

时间:2018-06-04 11:32:44

标签: java oop inheritance interface

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

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;
    }
}

2 个答案:

答案 0 :(得分:0)

也许您正在寻找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;
}

现在您需要在getStatusA中实施B

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

答案 1 :(得分:0)

如果在接口中向方法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);
    }

}