您的位置:首页 > 财经 > 产业 > 【设计模式】【创建型5-4】【建造者模式】

【设计模式】【创建型5-4】【建造者模式】

2024/7/4 6:29:10 来源:https://blog.csdn.net/SHI_IHS/article/details/139994603  浏览:    关键词:【设计模式】【创建型5-4】【建造者模式】

文章目录

  • 建造者模式
    • 示例代码

建造者模式

可以在不同的构建过程中使用相同的建造者。

builder 链式调用创建对象就是建造者模式的使用

示例代码

public class Human {private int age;private String name;private int sex;@Overridepublic String toString() {return "Human{" +"age=" + age +", name='" + name + '\'' +", sex=" + sex +'}';}public static void main(String[] args) {Human wangshilei = HumanBuilder.aHuman().withName("wangshilei").withAge(100).withSex(1).build();System.out.println(wangshilei);}public static final class HumanBuilder {private int age;private String name;private int sex;private HumanBuilder() {}public static HumanBuilder aHuman() {return new HumanBuilder();}public HumanBuilder withAge(int age) {this.age = age;return this;}public HumanBuilder withName(String name) {this.name = name;return this;}public HumanBuilder withSex(int sex) {this.sex = sex;return this;}public Human build() {Human human = new Human();human.age = this.age;human.sex = this.sex;human.name = this.name;return human;}}
}//输出  Human{age=100, name='wangshilei', sex=1}

如上 就是实际的使用
构建复杂对象的时候使用 提高代码的可读性
我们可以隐藏构造细节。给外部提供简单的接口就能构建对象

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com