java对象设计模式之Builder模式探索

设计目的:解决代码的可读性

1605238665-31e12560ec8787f
1605238667-9d92b0a7db19951

常规构建一个对象,属性不清晰,若属性过多,就会模糊!

build模式如下(在原有类中构建一个静态内部类,此类作用主要用于展示):

1605238670-8db389da8a36607
1605238672-07987b505accd4d

即把属性先传到内部类,通过设置内部类的属性,在传递给原始内的构造函数,在此中间,即可展示属性,对比如下:

1605238674-05cb6a7ba274942

原始代码:

package com.wpwet.test.mode;

public class Person {

    private String name;
    private Integer age;
    private Integer score;
    private Double wight;
    private Double heiht;

    public Person(String name, Integer age, Integer score, Double wight, Double heiht) {
        this.name = name;
        this.age = age;
        this.score = score;
        this.wight = wight;
        this.heiht = heiht;
    }

    public Person (Build build){
        this.name  = build.name;
        this.age   =  build.age;
        this.score =  build.score;
        this.wight =  build.wight;
        this.heiht =  build.heiht;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }

    public Double getWight() {
        return wight;
    }

    public void setWight(Double wight) {
        this.wight = wight;
    }

    public Double getHeiht() {
        return heiht;
    }

    public void setHeiht(Double heiht) {
        this.heiht = heiht;
    }

    static class Build{
        private String name;
        private Integer age;
        private Integer score;
        private Double wight;
        private Double heiht;

        public Build name(String name){
            this.name = name;
            return this;
        }
        public Build age(Integer age){
            this.age = age;
            return this;
        }
        public Build score(Integer score){
            this.score = score;
            return this;
        }
        public Build wight(Double wight){
            this.wight = wight;
            return this;
        }
        public Build heiht(Double heiht){
            this.heiht = heiht;
            return this;
        }

        public Person build( ){
            return new Person(this);
        }

    }



    public static void main(String[] args) {
        Person person = new Person("xiaoing",10,90,32.0,90.0);
        Person person1 = new Build().name("xiaoming").age(16).heiht(90.0).score(90).wight(32.0).build();
    }
}
1.本站所有资源收集于互联网,仅用于学习和研究,若用于违法,与本站无关,仅限学习交流请勿用于商业用途。 2.会员在本站下载的VIP素材后,只拥有使用权,著作权归原作者及49vps所有。 3.VIP素材,未经合法授权,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。 4.如果素材损害你的权益,请联系客服删除。
49资源网 » java对象设计模式之Builder模式探索