java - 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.
解决方案
您可以将逻辑封装在返回对象实例本身的 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
推荐阅读
- java - 表格布局中不需要的行
- javascript - 有没有办法在 TypeScript 的新类中扩展 String?
- arrays - Subset Sum Problem [Nested Loop Solution?]
- reportlab - 使用reportlab创建具有动态行和列的表时出现问题
- linux - awk:输出文件太多 10 记录号 12
- html - cookie 名称可以以数字开头吗?
- c++ - 有没有办法使成员函数不能从构造函数调用?
- typescript - 是否可以推断出通用索引签名的类型?
- c# - 为什么 ReaderWriterLockSlim 在 EnterReadLock() 内部调用 Sleep()?
- jquery - 是否可以在每次页面刷新时仅刷新#content div?