Builder模式是一步一步创建一个复杂对象的创建型模式,它允许用户在不知道内部构建细节的情况下,可以更精细的控制对象的构造流程。
也就是将一个对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
1,相同的方法,不同的执行顺序,产生不同的事件结果时
2,多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不相同时
3,产品类非常复杂,或者产品类中的调用顺序不同产生了不同的作用,这个时候使用Builder模式非常合适
4,当初始化一个对象特别复杂,如参数多,且很多参数都具有默认值时
假如我们有一个视频播放器,这个播放器初始化的时候可以设置默认图,视频标题,视频链接。
那我们使用Builder模式如下:
新建一个接口,定义视频播放器的功能:
- public interface IVideoView {
- /**
- * 设置视频标题
- * */
- void setTitle(String title);
-
- /**
- * 设置视频封面
- * */
- void setImage(String img);
-
- /**
- * 设置视频链接
- * */
- void setUrl(String url);
- }
新建一个播放器实现接口,内部定义一个Builder静态内部类,用来构建播放器:
- /**
- * 视频播放器
- * */
- 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);
- }
- }
- }
那么在使用的时候,就可以实现链式调用了:
- VideoView videoView = new VideoView.Builder()
- .setImage("http://dxxx/ddsd.jpg")
- .setTitle("视频")
- .setUrl("http://sdsdsds.mp4")
- .bulid();
这样就可以优雅的使用链式调用去创建我们的对象了。
AlertDialog:
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder
- .setIcon(R.drawable.ic_launcher_background)
- .setMessage("title")
- .create()
- .show();
优点:
1,封装性好,使用Builder模式可以使客户端不必知道产品内部组成的细节
2,建造者独立,容易扩展
缺点:
会产生多余的Builder对象,消耗内存