设计模式之创建者模式

概念

如果需要将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示意图时,我们需要一个应用于一个设计模式,创建者模式,又叫生成器模式

如果我们用了创建者模式,那么用户就只需指定需要创造的类型既可以得到他们,而具体建造的过程和细节就不需要知道了。

简单应用

场景:创建一个用户,账号和密码为必填项:

package com.haan.bulderpattern;

public class User {
    private String code;        //账号,必填
    private String password;    //密码,必填
    private String nickName;    //昵称,选填
    private int age;        //年龄,选填
    private int sex;        //性别,1:男性,0女性 ,选填


	//构造函数设置为private
    private User(String code, String password, String nickName, int age, int sex) {
        this.code = code;
        this.password = password;
        this.nickName = nickName;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "账号='" + code + '\'' +
                ", 密码='" + password + '\'' +
                ", 昵称='" + nickName + '\'' +
                ", 年龄=" + age +
                ", 性别='" + (sex==1?"男":"女") +
                "'}";
    }

    public static class UserBuilder {
        private String code;        //账号,必填
        private String password;    //密码,必填
        private String nickName;    //昵称,选填
        private int age;        //年龄,选填
        private int sex;        //性别,1:男性,0女性 ,选填

        //设置必填参数(账号,密码)
        public UserBuilder(String code, String password) {
            this.code = code;
            this.password = password;
        }

        //设置昵称
        public UserBuilder nickName(String nickName) {
            this.nickName = nickName;
            return this;
        }

        public UserBuilder age(int age) {
            this.age = age;
            return this;
        }

        public UserBuilder sex(int sex) {
            this.sex = sex;
            return this;
        }

        public User build() {
            //数据校验
            if (code==null||code.isEmpty())
                throw  new NullPointerException("code 为 null");
            if (password.length()<6)
                throw new RuntimeException("密码长度小于6");
            //设置默认值
            if (nickName==null||nickName.isEmpty())
                this.nickName="新和";
            return new User(code,password,nickName,age,sex);
        }
    }

}


测试:

package com.haan.bulderpattern;

public class testMain {
    public static void main(String[] args) {
        User user = new User.UserBuilder("123123", "12345678")
                .age(22)
                .sex(1)
                .build();
        System.out.println(user.toString());
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值