简体   繁体   中英

Java - inner private class only to encapsulate construction for outer class

Is this good practice to have class, that is inner class (not static), which only task is to construct and initiate object of outer class (in her constructor)? Lifetime of this class would be equal to lifetime of constructor of outer class.

Here is example:

OuterClass {
    // (...fields here...)
    private ConstructClass {
        // (...some useful methods and fields here...)
        public ConstructClass(String param1, int param2, ...) {
           // (...construction of OuterClass here...)
        }
    }
    public OuterClass(String param1, int param2, ...) {
        new ConstructClass(param1, param2, ...);
    }
}

It looks like to me like you tried to rediscover builder pattern :). You came pretty close to it, hovewer it would be much better if you changed your constructor to set single fields only, not to create the whole object.

Creating builder may cause some decrease in efficiency (additional memory in jvm has to be reserved), but it can largely reduce the amount of different parametrized constructors you have to create - the code is MUCH clearer this way. Modifying your code to fulfill the builder paradigm is worth taking into account, but the final decision is up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM