避免重复的 Java 设计模式



我有以下类

public class MyCustomFactory extends SomeOther3rdPartyFactory {
    // Return our custom behaviour for the 'string' type
    @Override
    public StringType stringType() {
        return new MyCustomStringType();
    }
    // Return our custom behaviour for the 'int' type
    @Override
    public IntType intType() {
        return new MyCustomIntType();
    }
    // same for boolean, array, object etc
}

现在,例如,自定义类型类:

public class MyCustomStringType extends StringType {
    @Override
    public void enrichWithProperty(final SomePropertyObject prop) {
        super.enrichWithProperty(prop);
        if (prop.getSomeAttribute("attribute01")) {
            this.doSomething();
            this.doSomethingElse();
        }
        if (prop.getSomeAttribute("attribute02")) {
            this.doSomethingYetAgain();
        }
        // other properties and actions
    }
}

但是每个自定义类型类(如上面的字符串类(可能具有完全相同的if (prop.getSomeAttribute("blah")) { // same thing; }

假设我要添加另一个属性,有没有一种很好的方法可以避免在每个需要它的自定义类型类中复制if语句? 我可以将每个 if 语句移动到实用程序类,但我仍然需要将调用添加到实用程序类中的方法。 我认为我们可以做得更好。

您可以创建Map<String, Consumer<MyCustomStringType>>,其中键是属性名称,值是方法调用。

public class MyCustomStringType extends StringType {
    private final Map<String, Cosnumer<MyCustomStringType>> map = new HashMap<>();
    {
        map.put("attribute01", o -> {o.doSomething(); o.doSomethingElse();});
        map.put("attribute02", MyCustomStringType::doSomethingYetAgain);
        // other properties and actions
    }
    @Override
    public void enrichWithProperty(final SomePropertyObject prop) {
        super.enrichWithProperty(prop);
        map.entrySet().stream()
            .filter(entry -> prop.getSomeAttribute(entry.getKey()))
            .forEach(entry -> entry.getValue().accept(MyCustomStringType.this));
    }
}

根据初始化此类的方式(以及此映射是否始终相同(,您可能能够转换为静态最终不可变映射。

我还建议更好地命名它,但这里很大程度上取决于您的域以及此映射和循环的实际作用。

最新更新