When to use getInstanceOf instead of constructor

A few months ago, I attended a presentation organized by two representatives of an independent software development company. It was mainly about good software design and practice.

Two guys talked mostly about Java, and I remember how they said that in some cases it is very useful to use getInstanceOf () instead of the constructor. This is somehow connected with the fact that getInstanceOf () always called from different classes, and not from the constructor, and as it was much better for larger-scale projects.

As you can see, I cannot remember much about it now: / but I remember that the arguments they used were really convincing. I wonder if any of you have ever come across such a design, and when, will you say, is it useful? Or do you think that this is not so at all?

+3
source share
4 answers

They were probably talking about the static template of the factory method (rather than the reflection API method for dynamically creating objects).

There are several advantages of a method, such as getInstanceOf()over a constructor and with help new. The static factory method can ...

  • , ( , / ).

  • . Boolean.valueOf(boolean) Java API.

  • , - .

  • , (, , ). , , . :

    // This class will not compile!
    public class MyClass {
        public MyClass(String name, int max) {
            //init here
        }
        public MyClass(String name, int age) {
            // init here
        }
    }
    
    // This class will compile.
    public class MyClass2 {
        private MyClass2() {
        }
        public static MyClass2 getInstanceOfMax(String name, int max) {
            MyClass2 m2 = new MyClass2();
            // init here
            return m2;
        }
        public static MyClass2 getInstanceOfAge(String name, int age) {
            MyClass2 m2 = new MyClass2();
            // init here
            return m2;
        }
    }
    
  • .

  • , , ( ).

. .

:

  • factory , ; .

  • factory , () .

. , . , , factory. (, Java), .

+7

factory -Joshua Bloch

+10

, newInstance method . : MyClass foo = MyClass.newInstance();

; , , , , XML .

+1

Drew , newInstance() API Java Reflection. , .

Why it would be desirable to use it in a large project, the fact may arise that it leads to a Java Bean programming style and explicitly makes the creation of an object something concrete. In a large project, creating an object should not be a cross-cutting task, but rather a clearly defined responsibility, often from a single source / factory. But IMHO, you get all these benefits and more with the IoC template .

+1
source

Source: https://habr.com/ru/post/1731280/


All Articles