简体   繁体   English

实现抽象类的优雅方式

[英]Elegant way to implement abstract class

I have an abstract class with a single abstract method; 我有一个带有单个抽象方法的抽象类。 and a number of implementing classes (about 6). 和一些实现类(大约6个)。

The method returns an object that "needs" two parameters. 该方法返回一个“需要”两个参数的对象。

However, in some cases, only one of the two parameters is required. 但是,在某些情况下,仅需要两个参数之一。

Is there an elegant way to implement this case? 是否有一种优雅的方法来实现这种情况? (instead of return this parameter as empty) (而不是将此参数返回为空)

public class NormResult {
    protected List<String> normWords;
    protected  List<String> unNormWords;

    public NormResult(List<String> normWords,List<String> unNormWords) {
        this.normWords = normWords;
        this.unNormWords = unNormWords;
    }

    public NormResult(List<String> normWords) {
        this.normWords = normWords;
        this.unNormWords =  Collections.emptyList();
    }
}

public abstract class AbstractNormalizer {
    protected abstract List<NormResult> doNorm();
}

public class FirstNormImpl extends AbstractNormalizer {
    protected List<NormResult> doNorm() {
        List<String> normWords = new ArrayList<>(5);
        List<String> unNormWords = new ArrayList<>(7);

        NormResult result = new NormResult(normWords, unNormWords);
        return result;      
    }
}

public class SecondNormImpl extends AbstractNormalizer {
    protected List<NormResult> doNorm() {
        List<String> normWords = new ArrayList<>(8);    
        NormResult result = new NormResult(normWords);
        return result;
    }
}

if you do this to members final: 如果您对成员决赛这样做:

 protected final List<String> normWords;
 protected final List<String> unNormWords;

then in the constructor you have to initialize them both... then you can set to an empty collection or a null reference the one you dont have/need 然后在构造函数中必须将它们都初始化...然后可以将一个空集合或空引用设置为一个不需要/不需要的集合

and your overloaded constructor can look like: 您的重载构造函数可能如下所示:

public NormResult(List<String> normWords, List<String> unNormWords) {
    this.normWords = normWords;
    this.unNormWords = unNormWords;
}

public NormResult(List<String> normWords) {
    this(normWords, Collections.emptyList());
}

The two changes I would make: 我要进行的两个更改:

  • Make the fields final 最终确定字段
  • Use constructor telescoping 使用构造函数伸缩

as in: 如:

public NormResult(List<String> normWords) {
  this(normWords(), Collections.emptyList()); 
}

to avoid even that simple "code duplication" of assigning values twice. 避免两次分配值的简单“代码重复”。

Beyond that; 除此之外; I agree with the comments; 我同意这些意见。 this approach looks reasonable. 这种方法看起来很合理。

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

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