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

文章目录

建造者模式

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

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

示例代码

java 复制代码
public class Human {
    private int age;
    private String name;
    private int sex;
    @Override
    public 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}

如上 就是实际的使用

构建复杂对象的时候使用 提高代码的可读性

我们可以隐藏构造细节。给外部提供简单的接口就能构建对象

相关推荐
coderSong25681 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
Mr_Air_Boy2 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
豆沙沙包?2 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
年老体衰按不动键盘3 小时前
快速部署和启动Vue3项目
java·javascript·vue
咖啡啡不加糖3 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
liuyang-neu3 小时前
java内存模型JMM
java·开发语言
UFIT3 小时前
NoSQL之redis哨兵
java·前端·算法
刘 大 望3 小时前
数据库-联合查询(内连接外连接),子查询,合并查询
java·数据库·sql·mysql
怀旧,3 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法
大春儿的试验田4 小时前
Parameter ‘XXX‘ not found. Available parameters are [list, param1]
java