Builderģʽ

匿名 (未验证) 提交于 2019-12-02 23:47:01

还没有看过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方法能不能被架构认可,待测试

能够想到的是:

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

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!