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

前端 未结 3 1319
轮回少年
轮回少年 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:30

    As long as it remains the only thing you do in the JobGroupMod constructor is is fairly safe as long as you understand the ramifications. There's a lot of Java code in the real world that does this. It's still not something you really want to do, especially when you start talking about multithreading and concurrency.

    The danger is passing this to something else before an object is fully constructed. If the constructor were to throw an exception after you did this and not fully construct, you could have a nasty problem. If another thread were to access the object you passed this to before it was fully constructed, you'd have a nasty problem.

    What you'll often find in Java is people using a factory pattern to avoid this, an "init" type method, or dependency injection.

    0 讨论(0)
  • 2021-02-14 07:39

    Generally there is no magic. You can either pass parameter via constructor or initalize it later using setter/init method etc.

    If your class JobMod needs reference to JobGroupMod and has nothing to do without it pass it using constructor. If sometimes it can stand without it create init() method or setter that can initialize this reference.

    BTW sometimes you have to create both parameterized and default constructor: first for regular programmatic usage, second if you are using XML, JSON or other serialization that is going easier for bean-like classes. In this case at least create javadoc that explains that default constructor should not be used directly.

    0 讨论(0)
  • 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<Job> clusterJobs) {
            JobGroup jg = new JobGroupMod();
            JobMod j = new JobMod(n, jg);
            return jg;
        }
    }
    
    0 讨论(0)
提交回复
热议问题