Java: Alternative to passing “this” as constructor argument in order to reference creating object

前端 未结 3 1326
轮回少年
轮回少年 2021-02-14 07:05

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

3条回答
  •  不思量自难忘°
    2021-02-14 07:55

    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 clusterJobs) {
            JobGroup jg = new JobGroupMod();
            JobMod j = new JobMod(n, jg);
            return jg;
        }
    }
    

提交回复
热议问题