简单入门建造者模式

建造者模式是设计模式的一种,将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

 

实用范围

1 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。[1] 

2 当构造过程必须允许被构造的对象有不同表示时。

 

介绍都是cp来的,直接上代码,建造者模式主要就是方便对对象的创建,管理,可以对对象中的field进行加工处理,在参数接收传递过程中是比较方便的~

 

package com.study.day;

/**
 * 建造者模式
 */
public class Desk {

    private String name;

    private Integer height;

    private Integer width;

    private String price;

    public Desk(Builder builder) {
        this.name = builder.name;
        this.height = builder.height;
        this.width = builder.width;
        this.price = builder.price;
    }

    public static Builder builder(){
        return new Builder();
    }

    public static class Builder{

        private String name;

        private Integer height;

        private Integer width;

        private String price;

        public Builder name(String name){
            this.name = name;
            return this;
        }

        public Builder height(Integer height){
            this.height = height;
            return this;
        }

        public Builder width(Integer width){
            this.width = width;
            return this;
        }

        public Builder price(String price){
            this.price = price;
            return this;
        }

        public Desk build(){
            return new Desk(this);
        }
    }

    @Override
    public String toString() {
        return "{" +
                "name='" + name + '\'' +
                ", height=" + height +
                ", width=" + width +
                ", price='" + price + '\'' +
                '}';
    }
}


下面简单的调用下~

package com.study.day;

import sun.security.krb5.internal.crypto.Des;

public class DeskMain {
    public static void main(String[] args) {
        Desk desk = Desk.builder()
                .name("方桌")
                .height(130)
                .width(100)
                .price("100元")
                .build();
        System.out.println("构造的桌子:"+desk.toString());
    }
}

 

 

 

结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笔下天地宽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值