Builder(建造者)模式

来源:互联网 发布:双色球算法必中6红球 编辑:程序博客网 时间:2024/05/19 07:11

一.定义

将一个复杂对象的构建和它的标识分离,使得同样的构建过程可以创建不同的表示。

解释一下:该模式是为了将具体对象的构建过程对使用者封闭,使用者只需配置好相应的部件信息,而不用知道里面是怎么回事。建造者模式很常见,例如AlertDialog的创建,Universal-Image-Loader,okhttp,Glide的内部等等;当然里面的属性信息都有默认的值,你不配置也能实现简单的功能,想要优化则要自己配置。

二.优缺点

2.1好处:

1.避免使用者在使用工具类的时候因为里面的函数过多而烦恼(不知道该配置哪个好)

2.避免在不同的使用地点对工具类做“随意”的改动,配置过程在初始化的时候就做好

3.良好封装性,使用者只要给出配置信息即可,不用管里面的运行细节

4.建造者独立,容易扩展

2.2缺点:

会产生多余的Builder对象和工具类对象(提供给使用者的工具主类)

三.这里举个例子

电脑由cpu,主板,显示器做成。现在我想组装一个电脑

我要的工具类Computer,让他帮我组装一台电脑,有默认的配置,想定制我要自己配置

public class Computer {    private Board board;    private Cpu cpu;    private DisPlay disPlay;    //private的,外面拿不到实例,只能通过建造者拿到实例    private Computer(Board board, Cpu cpu, DisPlay disPlay){        this.board = board;        this.cpu = cpu;        this.disPlay = disPlay;    }    public void start(){        Log.e("ComputerInfo", "Cpu==" + cpu.info + "---BOard" + board.info + "---Display==" + disPlay.info);    }    //建造者,在里面有了默认的配置    public static class Builder{        private Board board = new Board("英伟达");        private Cpu cpu = new Cpu("arm");        private DisPlay disPlay = new DisPlay("LG");        public Builder setBoard(Board board) {            this.board = board;            return this;        }        public Builder setCpu(Cpu cpu) {            this.cpu = cpu;            return this;        }        public Builder setDisPlay(DisPlay disPlay) {            this.disPlay = disPlay;            return this;        }        public Computer build(){            return new Computer(board, cpu, disPlay);        }    }}//Cpu组件类public class Cpu {    public String info;    public Cpu(String str){        info = str;    }}//主板类public class Board {    public String info;    public Board(String info){        this.info = info;    }}//显示器类public class DisPlay {    public String info;    public DisPlay(String info){        this.info = info;    }}

下面是使用方法,简单易用

//使用方法new Computer.Builder().setCpu(new Cpu("intel")).build().start();

下面是log

11-02 16:45:47.998 15312-15312/com.example.gongxiaoou.myapplication E/ComputerInfo: Cpu==intel---BOard英伟达---Display==LG

当然上面只是一个简单的demo,只是为了简单说明建造者模式