Java设计模式,以避免重复

问题描述 投票:1回答:1

我有以下课程

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

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

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

java design-patterns
1个回答
2
投票

您可以创建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));
    }
}

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

我还建议更好地命名它,但这里有很多取决于你的域以及这个map和loop实际上做了什么。

© www.soinside.com 2019 - 2024. All rights reserved.