Several ways to create and destroy objects in Java __java

Source: Internet
Author: User
several ways to create objectsConstructor static factory method via Builder
Instead of directly generating the desired object, the client invokes the constructor with all the necessary parameters to get a Builder object, and then the client invokes a setter-like method on the builder object to set each optional parameter and finally the parameterless build () on the client. method to build the object. The following is a simple example:
Builder pattern public class nutritionfacts{private final int servingsize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;


    private final int carbohydrate;
        public static class builder{//required private final int servingsize;

        private final int servings;
        Optional private int calories = 0;
        private int fat = 0;
        private int sodium = 0; private int Carbohydrate =0 public Builder (int servingsize, int servings) {this.servingsize = serving
            Size;
        This.servings=servings;
            Public Builder calories (int val) {calories=val;
        return this;
            Public Builder fat (int val) {fat=val;
        return this;
            Public Builder Sodium (int val) {sodium=val;
        return this; } public Builder carbohydrate (int vaL) {carbohydrate=val;
        return this;
        //build construct object public nutritionfacts built () {return new nutritionfacts (this);
        } private Nutritionfacts (Builder Builder) {servingsize = builder.servingsize;
        servings = builder.servings;
        calories = builder.calories;
        Fat = Builder.fat;
        Sodium = Builder.sodium;
    Carbohydrate = builder.carbohydrate; The//client invokes Nutritionfacts CocaCola = new Nutritionfacts.builder (8). Calories (m). Sodium (a). Carbohydrate (27). Build ();

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.