[英]How can I avoid writing many very similar setter methods?
I am working on a piece of code where the following applies: 我正在编写适用于以下条件的一段代码:
Each of these objects will then get their own setter in Class B, which corresponds 1:1 to the objects created in the instance of Class A ie In class A: 这些对象中的每一个将在类B中获得自己的设置器,该设置器与在类A的实例(即在类A中)创建的对象1:1相对应。
B b = new B(); final SomethingA somethingA1 = new SomethingA("input1"); b.setSomethingA(); ... final SomethingB somethingB15 = new SomethingB("input15"); b.setSomethingB15(); ... final SomethingA somethingA23 = new SomethingA("input23"); b.setSomethingA23();
Where all "somethings" inherit from the same class. 所有“事物”都继承自同一类。
The setter does nothing but: 设置员除了:
public void setSomethingX(somethingX){ this.somethingX = somethingX; }
I really do not want to write 23 setters that all do almost the same. 我真的不想写全部都差不多的23个二传手。 Is there something like a multi-purpose setter?
有像多功能塞特机吗?
The context of this is preparing an HTTP response in a very specific context and using some very specific frameworks. 其上下文是在非常特定的上下文中准备HTTP响应,并使用一些非常特定的框架。 Apparently, this way of doing saves lot of work somewhere else (that I have no influence on).
显然,这种方式节省了其他地方的很多工作(我对此没有影响)。 Also, as you can probably tell I am a novice developer.
另外,您可能会说我是新手开发人员。
I'd use Lombok setter/getter for this. 我会为此使用Lombok setter / getter 。
A single annotation that would trigger the creation of those methods. 单个注解将触发这些方法的创建。 The source code in your IDE will not be polluted with those setters and a lot easier to read.
这些设置程序不会污染您IDE中的源代码,并且更易于阅读。
There is a proposal for data classes, but not yet implemented FYI. 有关于数据类的建议 ,但尚未实施。
There are couple technics to reduce setters: 有一些技术可以减少二传手:
1) Create constructor with B as parameter 1)使用B作为参数创建构造函数
class A {
private B b;
public A(B b) {
this.b = b;
}
}
A a = new A(new B());
2) Use builder pattern (with lombok will be easy to implement): 2)使用构建器模式(使用龙目岛将很容易实现):
@Builder // lombok annotation
class A {
private B b;
}
A a = A.builder().withB(b).build();
3) Use factory method: 3)使用工厂方法:
class A {
private B b;
public static A newInstance(B b) {
A a = new A();
a.b = b;
return a;
}
}
A a = A.newInstance(new B());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.