首页 > 解决方案 > Returning an Object after setting another property in a single line

问题描述

Is there a way I could write the below code within the method in a single line, there is no issue with the code but just curious

public MyObject getObj(String name){
  MyObj myObj = PoolInstance.get(name);
  myObj.setFound(true);
  return myObj;
}

For some reason I cannot modify the PoolInstance.

标签: javajakarta-ee

解决方案


您可以将逻辑封装在返回对象实例本身的 setter 中:

class MyObject {

    private boolean found;

    public MyObject withFound(boolean isFound) {
        this.found = isFound;
        return this;
    }
}

客户端代码:

public MyObject getObj(String name){
   return PoolInstance.get(name).withFound(true);
}

还可以考虑使用 GoFBuilder设计模式来获得更惯用和更灵活的代码:Builder pattern example with explanation


推荐阅读