Article 2: when encountering multiple constructor parameters, consider using the builder)

Source: Internet
Author: User

 

Builder pattern ):

View code

Package Edu. SJTU. erplab. builder; 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; // constructor, static internal class public static class builder {// required parameter private final int servingsize; private final int servings; // optional parameter private int calories = 0; private int fat = 0; private int carbohydrate = 0; private int sodium = 0; Public Builder (INT servingsize, int servings) {This. servingsize = servingsize; this. servings = servings;} public builder calories (INT Val) {calories = val; return this; // return the builder class object itself, to link the call} public builder fat (INT Val) {fat = val; return this;} public builder carbohydrate (INT Val) {carbohydrate = val; return this ;} public builder sodium (INT Val) {sodium = val; return this;} public nutritionfacts build () {return New nutritionfacts (this) ;}} private nutritionfacts (Builder) {servingsize = builder. servingsize; servings = builder. servings; calories = builder. calories; fat = builder. fat; sodium = builder. sodium; carbohydrate = builder. carbohydrate ;}@ override Public String tostring () {// todo auto-generated method stub return "[" + "servingsize:" + servingsize + ", servings: "+ servings +", calories: "+ calories +", fat: "+ Fat +", sodium: "+ sodium +", carbohydrate: "+ carbohydrate +"] ";} public static void main (string [] ARGs) {nutritionfacts cocacola = new nutritionfacts. builder (240, 8 ). calories (100 ). sodium (35 ). carbohydrate (27 ). build (); system. out. println (cocacola );}}

 

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.