设计模式(三)---建造者模式

吐槽

emmmmm学校的课程有毒啊啊啊,所以就还有去学java后台去写接口,所以,,,还是加油吧

什么叫构建者模式

就是类似流水线工程一样,装配一个汽车,因为一辆汽车有很多的部分,所以装配的时候很费时间,我们又想把各种部件自定义一下,比如换个红色的车框,好点的轮胎等等。
所以就需要构建者模式
将一个复杂对象的构建与它的表示分离,使得同样的构造过程可以创建不同的表示

使用的场景

  • 相同的方法,不同的执行顺序,产生不同的事件结果时候
  • 多个部件或者零件,都可以装配上一个对象里面,但是产生的运行结果又不同时候
  • 产品类非常复杂,或者产品类中的调用顺序不同产生不同的效果
  • 当初始化一个对象特别复杂,参数特别多的时候,且很多参数有默认值的时候

使用过程

角色

  • Product产品类—–产品的抽象类
  • Builder —–抽象Buider类—–规范产品的组建,一般是由子类实现的组建过程
  • ConcreteBuilder—–具体的Builder类
  • Director——统一的组装过程

这里写图片描述

创建过程

就是类似创建个一个叫什么的学生,长的什么样的样子,穿什么

1 创建产品类 Student.java

/**
 * 构建者模式的产品类
 */
public class Student {
    private String name;

    private String face;

    private String clothers;

    public void setName(String name) {
        this.name = name;
    }

    public void setClothers(String clothers) {
        this.clothers = clothers;
    }

    public void setFace(String face) {
        this.face = face;
    }

    String showMsg(){
        return "这里有个叫" + name + "的小学生" + "长的一张" + face + "穿着一身" + clothers + "哈哈哈哈";
    }
}

2 创建抽象Builder接口:Builderinterface.java

**
 * 抽象接口
 */
public interface Builderinterface {
    void setName(String name);

    void setFace(String face);

    void setClothers(String clothers);


    Student build();
}

3 创建接口实现类:ConcreteBuider.java

**
 * 接口实现类
 */
public class ConcreteBuider implements Builderinterface {
   private Student mstudent = new Student();
    @Override
    public void setName(String name) {
        mstudent.setName(name);
    }

    @Override
    public void setFace(String face) {
        mstudent.setFace(face);

    }

    @Override
    public void setClothers(String clothers) {
        mstudent.setClothers(clothers);

    }

    @Override
    public Student build() {
        return mstudent;
    }
}

4 .创建构建过程类:Director.java

**
 * 构造过程类
 */
public class Director {
    private Builderinterface mbuilderinterface = null;

    Director(Builderinterface builderinterface){
        this.mbuilderinterface = builderinterface;
    }

    Student createCharacter(String name, String face, String clothers){
        this.mbuilderinterface.setName(name);
        this.mbuilderinterface.setFace(face);
        this.mbuilderinterface.setClothers(clothers);

        return mbuilderinterface.build();
    }
}

5 主函数调用

  //测试构造者模式

        //先new接口
        Builderinterface builderinterface = new ConcreteBuider();
        //创建构建过程对象
        Director director = new Director(builderinterface);
        //创建学生对象
        Student student = director.createCharacter("笑笑","正太脸","格子衬衣");
        Log.d("233",student.showMsg());

运行结果

这里写图片描述

总结

这个逻辑还是蛮清晰的,Builder接口和Director构建实现类一起将一个复杂的产品生产的过程,对外隐藏了构造细节,同样的构造方法可以创建不同的对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值