Effective Java chapter II objects (1)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.