设计模式之Builder模式

下面是简单的应用场景:组装电脑


Computer类


public class Computer {
    private String cpu; // cpu
    private String graphicsCard; // 显卡
    private String motherBoard; // 主板
    private String memory; // 内存
    private String hardDsik; // 硬盘
    private String display; // 显示器



    // 打印验证
    @Override
    public String toString() {
        return "Computer [cpu=" + cpu + ", graphicsCard=" + graphicsCard
                + ", motherBoard=" + motherBoard + ", memory=" + memory
                + ", hardDsik=" + hardDsik + ", display=" + display + "]";
    }




    public static class Builder {
        // 默认值
        private String cpu = "i5"; // cpu
        private String graphicsCard = "N卡"; // 显卡
        private String motherBoard = "技嘉"; // 主板
        private String memory = "8G"; // 内存
        private String hardDsik = "128G"; // 硬盘
        private String display = "华硕"; // 显示器
        public Builder setCpu(String cpu) {
            this.cpu = cpu;
            return this;
        }
        public Builder setGraphicsCard(String graphicsCard) {
            this.graphicsCard = graphicsCard;
            return this;
        }
        public Builder setMotherBoard(String motherBoard) {
            this.motherBoard = motherBoard;
            return this;
        }
        public Builder setMemory(String memory) {
            this.memory = memory;
            return this;
        }
        public Builder setHardDsik(String hardDsik) {
            this.hardDsik = hardDsik;
            return this;
        }
        public Builder setDisplay(String display) {
            this.display = display;
            return this;
        }

        // 应用设置
        void applyConfig(Computer computer) {
            computer.cpu = this.cpu;
            computer.graphicsCard = this.graphicsCard;
            computer.motherBoard = this.motherBoard;
            computer.memory = this.memory;
            computer.hardDsik = this.hardDsik;
            computer.display = this.display;
        }

        // 创建
        public Computer create() {
            Computer computer = new Computer();
            applyConfig(computer);
            return computer;
        }

    }


}

使用

// Builder模式
        Computer computer = new Computer.Builder().setCpu("i7").create();

Builder模式的好处:
1.减少大量不必要的get,set方法,并且这种做法规定了只有在初始化的时候可以设置参数属性。用户不需要再开发过程中另外考虑是否改变属性参数。
2.良好的封装性,使用建造者模式可以使用户不需要知道内部细节也能够使用,因为内部初始化了参数属性。
3.独立,容易拓展。

Builder模式的缺点:
1.消耗内存,产生多余的Builder对象,消耗内存。


以上为我初学者的看法,如果有不足的地方欢迎指导。 : )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值