Java:代替传递“this”作为构造函数参数,以引用创建对象 [英] Java: Alternative to passing "this" as constructor argument in order to reference creating object
问题描述
我花了一会儿想到不同的解决方案,我去的时候,我读过(我还没有真正的Java经验),使用这个作为一个构造函数的参数通常不是一个好的做法。
我想做的是实例化JobGroupMod类的几个对象,对于每个JobGroupMod,我必须创建一定数量的JobMod对象,这些对象必须能够引用回来生成它们的JobGroupMod对象。
为了实现这一点,我将this传递给JobMod构造函数,但即使工作,它也不会像正确的设计。
>
public class JobGroupMod implements JobGroup {
public JobGroupMod(Node n,Set< Job> clusterJobs){
JobMod j = new JobMod(n,this);
}
}
现在JobMod类:
public class JobMod implements Job {
public JobMod(Node n,JobGroup jg){
setJobGroup(jg);
}
}
我的问题是,有更好的解决方法
您应该尝试使用静态工厂方法(有效的Java连结)。
这样,您可以避免在构造函数调用中传递
,这是非常不值得说的。
示例代码: / p>
public class JobGroupMod implements JobGroup {
public static JobGroupMod createModeMod(Node n,Set< Job> clusterJobs ){
JobGroup jg = new JobGroupMod();
JobMod j = new JobMod(n,jg);
return jg;
}
}
I've spent a while thinking about different solutions that the one I went for as I've read around (I am not really experienced with Java yet) that using this for a constructor argument isn't usually a good practice.
What I am trying to do is to instantiate several objects of class JobGroupMod and for every JobGroupMod I have to create a certain number of JobMod objects that must be able to reference back the JobGroupMod objects in which they've been spawned from.
In order to accomplish that I am passing "this" to the JobMod constructor but, even if working, it didn't feel like proper designing.
public class JobGroupMod implements JobGroup {
public JobGroupMod(Node n,Set<Job> clusterJobs){
JobMod j=new JobMod(n,this);
}
}
And now the JobMod class:
public class JobMod implements Job {
public JobMod(Node n, JobGroup jg){
setJobGroup(jg);
}
}
My question is, is there a better way of solving this, or is my solution the suggested way?
You should try using a static factory method (Effective Java link).
This way you avoid passing this
in a constructor call, which is highly ill-advised to say the least.
example code:
public class JobGroupMod implements JobGroup {
public static JobGroupMod createModeMod(Node n, Set<Job> clusterJobs) {
JobGroup jg = new JobGroupMod();
JobMod j = new JobMod(n, jg);
return jg;
}
}
这篇关于Java:代替传递“this”作为构造函数参数,以引用创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!