Builder模式

Posted xiangzhahao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Builder模式相关的知识,希望对你有一定的参考价值。

还没有看过Builder模式的作用,看过一篇介绍Builder模式的文章,这里是关于Builder模式的思考:思考是否有比新建一个内部类更好的方法,首先想到的是

package xyz.n490808114.test;
public class  BuilderTest
    String name;
    int age;
    int high;
    int weight;
    int speed;

    public BuilderTest name(String name)
        this.name = name;
        return this;
    
    public BuilderTest age(int age)
        this.age = age;
        return this;
    
    public BuilderTest high(int high)
        this.high = high;
        return this;
    
    public BuilderTest weight(int weight)
        this.weight = weight;
        return this;
    
    public BuilderTest speed(int speed)
        this.speed = speed;
        return this;
    
    public void setName(String name)this.name = name;
    public void setAge(int age)this.age = age;
    public void setHigh(int high)this.high = high;
    public void setWeight(int weight)this.weight = weight;
    public void setSpeed(int speed)this.speed = speed;
    public String getName()return this.name;
    public int getAge()return this.age;
    public int getHigh()return this.high;
    public int getWeight()return this.weight;
    public int getSpeed()return this.speed;
    public static void main(String[] args) 
        BuilderTest t = new BuilderTest().age(20).speed(50);
        System.out.println(t.name);
        System.out.println(t.age);
        System.out.println(t.high);
        System.out.println(t.weight);
        System.out.println(t.speed);
    

输出为

null
20
0
0
50

这样感觉跟set方法重复太多,整合一下,如下

package xyz.n490808114.test;
public class  BuilderTest
    String name;
    int age;
    int high;
    int weight;
    int speed;
    public BuilderTest setName(String name)this.name = name;return this;
    public BuilderTest setAge(int age)this.age = age;return this;
    public BuilderTest setHigh(int high)this.high = high;return this;
    public BuilderTest setWeight(int weight)this.weight = weight;return this;
    public BuilderTest setSpeed(int speed)this.speed = speed;return this;
    public String getName()return this.name;
    public int getAge()return this.age;
    public int getHigh()return this.high;
    public int getWeight()return this.weight;
    public int getSpeed()return this.speed;
    public static void main(String[] args) 
        BuilderTest t = new BuilderTest().setAge(20).setSpeed(50);
        System.out.println(t.name);
        System.out.println(t.age);
        System.out.println(t.high);
        System.out.println(t.weight);
        System.out.println(t.speed);
    

这样只是精简代码,只是不知道这样的set方法能不能被spring认可,待测试

能够想到的是:

1,Builder模式用内部类的方法,可以用来修改现有代码,不改动,不新增类的方法,仅在创建时使用内部类;

2,猜测:如果不是频繁创建的话,对性能的影响不大;

3,如果不采用模式,仅使用set方法的话,代码量会多,但是代码会更清晰;

4,Builder模式使代码更易阅读。

以上是关于Builder模式的主要内容,如果未能解决你的问题,请参考以下文章

关于Builder模式

构造者模式(builder)

建造者模式(Builder)

Java设计模式--------建造者模式(Builder模式)

设计模式之建造者(Builder)模式

Builder模式