Android设计模式--Builder建造者模式

一,定义

Builder模式是一步一步创建一个复杂对象的创建型模式,它允许用户在不知道内部构建细节的情况下,可以更精细的控制对象的构造流程。

也就是将一个对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

二,使用场景

1,相同的方法,不同的执行顺序,产生不同的事件结果时

2,多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不相同时

3,产品类非常复杂,或者产品类中的调用顺序不同产生了不同的作用,这个时候使用Builder模式非常合适

4,当初始化一个对象特别复杂,如参数多,且很多参数都具有默认值时

三,使用Builder模式

假如我们有一个视频播放器,这个播放器初始化的时候可以设置默认图,视频标题,视频链接。

那我们使用Builder模式如下:

新建一个接口,定义视频播放器的功能:

java 复制代码
public interface IVideoView {
    /**
     * 设置视频标题
     * */
    void setTitle(String title);

    /**
     * 设置视频封面
     * */
    void setImage(String img);

    /**
     * 设置视频链接
     * */
    void setUrl(String url);
}

新建一个播放器实现接口,内部定义一个Builder静态内部类,用来构建播放器:

java 复制代码
/**
 * 视频播放器
 * */
public class VideoView implements IVideoView{
    private static final String TAG = "VideoView";

    private String title;

    private String img;

    private String url;

    public VideoView(Builder builder) {
        this.title = builder.title;
        this.img = builder.img;
        this.url = builder.url;
    }

    @Override
    public void setTitle(String title) {
        Log.d(TAG,"title:"+title);
    }

    @Override
    public void setImage(String img) {
        Log.d(TAG,"img:"+img);
    }

    @Override
    public void setUrl(String url) {
        Log.d(TAG,"url:"+url);
    }

    public static class Builder{

        private String title;

        private String img;

        private String url;

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

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

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

        public VideoView bulid(){
            return new VideoView(this);
        }
    }
}

那么在使用的时候,就可以实现链式调用了:

java 复制代码
VideoView videoView = new VideoView.Builder()
        .setImage("http://dxxx/ddsd.jpg")
        .setTitle("视频")
        .setUrl("http://sdsdsds.mp4")
        .bulid();

这样就可以优雅的使用链式调用去创建我们的对象了。

四,安卓中的使用案例

AlertDialog:

java 复制代码
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
        .setIcon(R.drawable.ic_launcher_background)
        .setMessage("title")
        .create()
        .show();

五,总结

优点:

1,封装性好,使用Builder模式可以使客户端不必知道产品内部组成的细节

2,建造者独立,容易扩展

缺点:

会产生多余的Builder对象,消耗内存

相关推荐
雪度娃娃15 小时前
设计模式-UML
设计模式
kyriewen1115 小时前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
开发语言·前端·javascript·设计模式·ecmascript
geovindu1 天前
go: Mediator Pattern
设计模式·golang·中介者模式
kyriewen1 天前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
Pkmer2 天前
古法编程: 适配器模式
java·设计模式
灰子学技术2 天前
Envoy 使用的设计模式技术文档
设计模式
Carl_奕然3 天前
【智能体】Agent的四种设计模式之:ReAct
人工智能·设计模式·语言模型
二哈赛车手3 天前
新人笔记---多策略搭建策略执行链实现RAG检索后过滤
java·笔记·spring·设计模式·ai·策略模式
楼田莉子3 天前
仿Muduo的高并发服务器:Channel模块与Poller模块
linux·服务器·c++·学习·设计模式