This chapter mainly describes the creation and destruction of objects, how to avoid unnecessary, too many objects, as well as several methods of creating objects
One. Use the static factory method instead of the constructor,
normal methods for creating classes Oneobject oneobject=new oneobject (); In this case, a new object is created every time.
Static Factory method
public class Oneobject {
private static Oneobject oneobject=new oneobject ();
private String name;
public static Oneobject Getoneobject () {
return oneobject;
};
}
1. In this case, no matter how many times getoneobject () is used, there is only one Oneobject object
2. In addition to a method, GetOneObject2, where Towobject,threeobjectshix is a subclass object of Oneobject
public static Oneobject GetOneObject2 (Integer type) {
if (type==1) {
return new Towobject ();
}
else{
return new Threeobject ();
}
};
This will generate oneobject different subclasses depending on the parameters.
The book says there are a few benefits, what name is good to remember Ah, and so on the list of meaningless
Two. When a bean has many properties, consider using the builder
Package theone;
public class Twoobject {
private int A;
private int B;
private int C;
public static class Bulider {
private int A;
private int B;
private int C;
Public Bulider A (int a) {
THIS.A = A;
return this;
}
Public Bulider B (int b) {
this.b = b;
return this;
}
Public Bulider C (int c) {
THIS.C = C;
return this;
}
Public Twoobject Bulid () {
return new Twoobject (this);
}
}
Public Twoobject (Bulider b) {
THIS.A=B.A;
this.b=b.b;
THIS.C=B.C;
}
public static void Main (string[] args) {
Twoobject to=new Twoobject.bulider (). A (1). B (2). Bulid ();
System.out.println (TO.A);
}
}
This writing is more readable, but there are some drawbacks, is the construction of Bulider when the overhead is slightly higher, if the performance-oriented situation, it is not necessary to consider
Effective Java chapter II objects (1)