首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免重复的Java设计模式

避免重复的Java设计模式
EN

Stack Overflow用户
提问于 2018-03-03 00:23:21
回答 1查看 96关注 0票数 1

我有以下课程

代码语言:javascript
复制
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
}

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

代码语言:javascript
复制
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语句移到实用程序类中,但我仍然需要将调用添加到实用程序类中的方法。我想我们可以做得更好。

EN

回答 1

Stack Overflow用户

发布于 2018-03-03 00:31:44

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

代码语言:javascript
复制
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和循环的实际作用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49073228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档