设计模式之建造者模式

设计模式之建造者模式

建造者模式使用多个简单对象一步步构建成一个复杂的对象,他提供一种创建复杂对象的最佳方式

实现方式

proudct:最终要生成的对象

builder:构建者的抽象基类,其中定义了构建实体对象的抽象步骤,其实体类需要实现这些步骤,其中会有个方法getProduct() 返回最终生成的实体对象

ConcreteBuilder:builder的实现对象

Director(导演):决定如何构建最终产品的算法,其中包含了组装的方法,在这里会调用builder的方法,就可以设置builder,设置完成后就可以通过builder getproduct()的方法获取最终的产品

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2EKiYlbW-1645083203404)(C:\Users\lihongzhe\AppData\Roaming\Typora\typora-user-images\image-20220217144649728.png)]

步骤一下面以手机为例子我们创建一个phone类

public class Phone {
    private String cpu ;//必须
    private String size;//必须
    private String headSet;//可选 耳机
    private String portableBattery;//可选 充电宝


    public Phone(String cpu, String size) {
        this.cpu = cpu;
        this.size = size;
    }
    public void setHeadSet(String headSet) {
        this.headSet = headSet;
    }
    public void setPortableBattery(String portableBattery) {
        this.portableBattery = portableBattery;
    }

    @Override
    public String toString() {
        return "Phone{" +
                "cpu='" + cpu + '\'' +
                ", size='" + size + '\'' +
                ", headSet=" + headSet +
                ", portableBattery='" + portableBattery + '\'' +
                '}';
    }
}

步骤二抽象构建者类

public abstract class PhoneBuilder {
    public abstract PhoneBuilder setheadSet();
    public abstract PhoneBuilder setportableBattery();

    public abstract  Phone getPhone();

}


步骤三 创建Director

public class PhoneDirector {
    public void makePhone(PhoneBuilder phoneBuilder){
        phoneBuilder.setheadSet().setportableBattery();

    }

}

步骤四 实体构建者类
ublic class ApplePhoneBuilder extends PhoneBuilder
{

    private Phone phone;



    public  ApplePhoneBuilder( String cpu, String sizz){
        phone = new Phone(cpu,sizz);
    }

    @Override
    public PhoneBuilder setheadSet() {
        phone.setHeadSet("苹果耳机");
        return this;
    }

    @Override
    public PhoneBuilder setportableBattery() {
        phone.setPortableBattery("苹果专用充电宝");
        return this;
    }

    @Override
    public Phone getPhone() {
        return phone;
    }
}

调试

public class MakerTest {
    public static void main(String[] args) {
        PhoneDirector phoneDirector = new PhoneDirector();
        ApplePhoneBuilder apple = new ApplePhoneBuilder("苹果内核", "12寸");
        phoneDirector.makePhone(apple);
        Phone phone = apple.getPhone();
        System.out.println(phone);//输出Phone{cpu='苹果内核', size='12寸', headSet=苹果耳机, portableBattery='苹果专用充电宝'}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值