学习设计模式之构建者模式

构建者模式主要是用在构建复杂对象中,将多个简单对象一步步构建成复杂对象。

首先创建Computer对象(复杂对象),其中包含几个简单对象:

public class Computer {
    //显示器
    private String xianshiqi;
    //主机
    private String zhuji;
    //鼠标
    private String shubiao;
    //键盘
    private String jianpan;
    //音响
    private String yinxaing;

    @Override
    public String toString() {
        return "Computer{" +
                "xianshiqi='" + xianshiqi + '\'' +
                ", zhuji='" + zhuji + '\'' +
                ", shubiao='" + shubiao + '\'' +
                ", jianpan='" + jianpan + '\'' +
                ", yinxaing='" + yinxaing + '\'' +
                '}';
    }

    public String getXianshiqi() {
        return xianshiqi;
    }

    public void setXianshiqi(String xianshiqi) {
        this.xianshiqi = xianshiqi;
    }

    public String getZhuji() {
        return zhuji;
    }

    public void setZhuji(String zhuji) {
        this.zhuji = zhuji;
    }

    public String getShubiao() {
        return shubiao;
    }

    public void setShubiao(String shubiao) {
        this.shubiao = shubiao;
    }

    public String getJianpan() {
        return jianpan;
    }

    public void setJianpan(String jianpan) {
        this.jianpan = jianpan;
    }

    public String getYinxaing() {
        return yinxaing;
    }

    public void setYinxaing(String yinxaing) {
        this.yinxaing = yinxaing;
    }
}

 ComputerBuilder对象,用来构建每个简单对象

public class ComputerBuilder {
    private Computer computer = new Computer();

    public void installXianshiqi(String xianshiqi) {
        computer.setXianshiqi(xianshiqi);
    }

    public void installShubiao(String shubiao) {
        computer.setShubiao(shubiao);
    }

    public void installJianpan(String jianpan) {
        computer.setJianpan(jianpan);
    }

    public void installYinxiang(String yinxiang) {
        computer.setYinxaing(yinxiang);
    }

    public void installZhuji(String zhuji) {
        computer.setZhuji(zhuji);
    }

    public Computer getComputer() {
        return computer;
    }
}

创建测试方法:

public static void main(String[] args) {
        ComputerBuilder computerBuilder = new ComputerBuilder();
        computerBuilder.installJianpan("键盘");
        computerBuilder.installShubiao("鼠标");
        computerBuilder.installXianshiqi("显示器");
        computerBuilder.installYinxiang("音响");
        computerBuilder.installZhuji("主机");
        System.out.println(computerBuilder.getComputer());
    }

打印结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值