consider replacing constructors with static factory methodsThe most common way to create an instance of a custom class is to use a constructor, but a class can have more than one constructor, and all constructors have the same name, and we can only differentiate the role of different constructors by parameters. In addition to using a constructor, you can also use the static Factory method, which returns an instance of the class, and the custom method can be named by itself, which makes it easy to distinguish the function of each method. Example:
public class CreateObject {
   int age
String name ;
Public CreateObject ( String name ) {
this. name = name;
}
   public CreateObject ( String name, int age) {
      this name = name;
this. Age = age;
}
   //....
&NBSP;&NBSP; public < Span lang= "en-US" style= "background-color:inherit; Color:rgb (127,0,85); Font-family:consolas ">static CreateObject Getinstancewithname (String name) {
return new CreateObject (name);
}
&NBSP;&NBSP; public < Span lang= "en-US" style= "background-color:inherit; Color:rgb (127,0,85); Font-family:consolas ">static CreateObject Getinstancewithnameandage (String name, int age) {
return new CreateObject (name, age );
}
&NBSP;&NBSP; public < Span lang= "en-US" style= "background-color:inherit; Color:rgb (127,0,85); Font-family:consolas ">static < Span lang= "en-US" style= "background-color:inherit; Color:rgb (127,0,85); Font-family:consolas ">void Main (String[]args ){
CreateObject createobject = new CreateObject (
CreateObject createObject2 = new CreateObject ( one);
CreateObject createObject3 = Createobject.getinstancewithname ( " mmm " );
CreateObject CreateObject4 = CreateObject. Getinstancewithnameandage ("MMM");
}
}
Static Factory method Benefits:1, the static factory method has the name 2, can be used to create a singleton mode, and the constructor will create a new instance each time 3, you can return any subclass of the class, so that the subclass can be implemented flexible instantiation
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Consider the use of static factory methods to replace constructors