Effective Java Learning Notes

Source: Internet
Author: User
Tags protected constructor

Create and destroy objects First: consider replacing constructors with static factory methods

For example:

 public Static Boolean ValueOf (boolean  b) {    return b?  Boolean.TRUE:Boolean.FALSE;}

Advantage:

    • has a name
    • You don't have to create a new object every time you call Them.
    • They can return objects of any subtype of the original return type
    • They make the code more concise when creating instances of parameterized types

Disadvantages:

    • Class cannot be overridden if it does not contain a public or protected constructor
    • They're not really any different from other static methods.
Second: consider using a constructor when you encounter multiple constructor parameters

For constructors or static methods with multiple arguments, it is customary to use the overlapping constructor (telescoping Constructor) mode

//Telescoping constructor Pattern public classpizzaingredients{Private Final intSalt//Optional    Private Final intChess//o    Private Final intsausage;//o    Private Final intflour;//Required    Private Final intwater;//R    ...         publicPizzaingredients (intflour,intWater) {         this(flour, water, 0); }     publicPizzaingredients (intflour,intwater,intSalt) {         this(flour, water, salt, 0); }     publicPizzaingredients (intflour,intwater,intSaltintChess) {         this(flour, water, salt, chess, 0); }     publicPizzaingredients (intflour,intwater,intSaltintChessintSausage) {         this. Flour =flour;  this. water=water;  this. salt=salt;  this. chess=chess;  this. sausage=sausage; }}

If you construct too many parameters this way the code will become difficult to write and difficult to Read.

The second approach is to use the JavaBeans mode, which is to set the default value for each parameter, and to add a setter method to each field, to call its corresponding setter method when setting a Value. however, JavaBean may be in an inconsistent state during the construction process, and JavaBeans mode prevents the class from being made immutable, which requires extra effort to ensure its thread Safety.

The third alternative is builder Mode. The client uses the necessary parameters to get a builder object, invokes a Setter-like method on the builder object, sets each relevant optional parameter, and finally calls the parameterless build method to build the immutable Object.

 public classpizzaingredients{Private Final intSalt//Optional    Private Final intChess//o    Private Final intsausage;//o    Private Final intflour;//Required    Private Final intwater;//R    ...         public Static classbuilder{//Required Parameters       Private Final intflour; Private Final intwater; //Optional        Private intSalt = 0; Private intChess = 0; Private intSausage = 0;  publicBuilder (intflour,intWater) { this. Flour =flour;  this. water=water; } publicBuilder Salt (intVal) {salt=val; return  this; } publicBuilder Chess (intVal) {chess=val; return  this; } publicBuilder Sausage (intVal) {sausage=val; return  this; } publicpizzaingredients build () {return NewPizzaingredients ( this)}
}
  
PrivatePizzaingredients (builder Builder) {
Flour = builder.flour;
Water = builder.water;
Salt = builder.salt;
Chess = builder.chess;
Sausage = builder.sausage;
}
}

Client code
pizzaingredients Pizza = new Pizzaingredients.builder (max.). salt (5). chess (. sausage). Build ();

The builder model has the advantage of variable parameters and no need to consider order. however, the builder mode is much more verbose than the overlapping constructor pattern, preferably in very good parameters.

Article Three: hardening the Singleton property with a private constructor or enumeration type

Three ways to achieve singleton:

1. Public static members are final fields

// Singleton with public final field  public class wills{    publicstaticfinalnew  Wills ();     Private Wills () {    };    ...}

2. Public members are static factory methods

// Singleton with static factory  public class wills{    privatestaticfinalnew  Wills ();     Private Wills () {    };      public Static Wills getinstance () {        return  INSTANCE;}    ...}

Both of these approaches are possible in the presence of a private method by means of the accessibleobject.setaccessible method. To protect against this attack, you can modify the constructor to throw an exception when the instance is created the second Time.

And each time a serialized instance is deserialized, a new instance is created, which declares that all instance domains are transient and provides a readresolve method.

3. Single-element Enumeration Type

// Enum Singleton-the Preferred Approach  public enum wills{    INSTANCE;    ...}

This method is functionally similar to the public domain method, but it is more concise and provides a free serialization mechanism, which absolutely prevents multiple instantiations. Single-element enumeration types have become the best way to implement Singleton.

Effective Java Learning Notes

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.