美文网首页设计模式
设计模式-builder(建造者模式)

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

作者: isLJli | 来源:发表于2020-04-14 17:30 被阅读0次

定义模式:
将构建过程和表示过程进行分离,让参数构建过程变得更加的简单和直观。

builder模式的实例:

  • okhttp
OkHttpClient okHttpClient= new OkHttpClient.Builder()
              .readTimeout(10, TimeUnit.SECONDS)
              .connectTimeout(10,TimeUnit.SECONDS)
              .build();

源码:
public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
public OkHttpClient() {
   this(new Builder());
}
//Builder.builder()方法调用这个构造函数并把builder传进来
OkHttpClient(Builder builder) {
this.dispatcher = builder.dispatcher;
this.proxy = builder.proxy;
...
}

public static final class Builder {
public Builder() {
  dispatcher = new Dispatcher();
  protocols = DEFAULT_PROTOCOLS;
  connectionSpecs = DEFAULT_CONNECTION_SPECS;
  proxySelector = ProxySelector.getDefault();
  cookieJar = CookieJar.NO_COOKIES;
  socketFactory = SocketFactory.getDefault();
  hostnameVerifier = OkHostnameVerifier.INSTANCE;
  certificatePinner = CertificatePinner.DEFAULT;
  proxyAuthenticator = Authenticator.NONE;
  authenticator = Authenticator.NONE;
  connectionPool = new ConnectionPool();
  dns = Dns.SYSTEM;
  followSslRedirects = true;
  followRedirects = true;
  retryOnConnectionFailure = true;
  connectTimeout = 10_000;
  readTimeout = 10_000;
  writeTimeout = 10_000;
}
public OkHttpClient build() {
  return new OkHttpClient(this);
}
}
}
  • Dialog
//显示基本的AlertDialog  
  private void showDialog(Context context) {  
      AlertDialog.Builder builder = new AlertDialog.Builder(context);  
      builder.setIcon(R.drawable.icon);  
      builder.setTitle("头部");  
      builder.setMessage("内容");  
      builder.setPositiveButton("Button1",  
              new DialogInterface.OnClickListener() {  
                  public void onClick(DialogInterface dialog, int whichButton) {  
                      setTitle("点击了对话框上的Button1");  
                  }  
              })
        .setNeutralButton("Button2",  
              new DialogInterface.OnClickListener() {  
                  public void onClick(DialogInterface dialog, int whichButton) {  
                      setTitle("点击了对话框上的Button2");  
                  }  
              });  
      builder.create().show();  // 构建AlertDialog, 并且显示
  } 
// AlertDialog
public class AlertDialog extends Dialog implements DialogInterface {
  // Controller, 接受Builder成员变量P中的各个参数
  private AlertController mAlert;

  // 构造函数
  protected AlertDialog(Context context, int theme) {
      this(context, theme, true);
  }

  // 4 : 构造AlertDialog
  AlertDialog(Context context, int theme, boolean createContextWrapper) {
      super(context, resolveDialogTheme(context, theme), createContextWrapper);
      mWindow.alwaysReadCloseOnTouchAttr();
      mAlert = new AlertController(getContext(), this, getWindow());
  }

  // 实际上调用的是mAlert的setTitle方法
  @Override
  public void setTitle(CharSequence title) {
      super.setTitle(title);
      mAlert.setTitle(title);
  }

  // 实际上调用的是mAlert的setCustomTitle方法
  public void setCustomTitle(View customTitleView) {
      mAlert.setCustomTitle(customTitleView);
  }

  public void setMessage(CharSequence message) {
      mAlert.setMessage(message);
  }

  // AlertDialog其他的代码省略

  // ************  Builder为AlertDialog的内部类   *******************
  public static class Builder {
      // 1 : 存储AlertDialog的各个参数, 例如title, message, icon等.
      private final AlertController.AlertParams P;
      // 属性省略

      /**
       * Constructor using a context for this builder and the {@link AlertDialog} it creates.
       */
      public Builder(Context context) {
          this(context, resolveDialogTheme(context, 0));
      }


      public Builder(Context context, int theme) {
          P = new AlertController.AlertParams(new ContextThemeWrapper(
                  context, resolveDialogTheme(context, theme)));
          mTheme = theme;
      }

      // Builder的其他代码省略 ......

      // 2 : 设置各种参数
      public Builder setTitle(CharSequence title) {
          P.mTitle = title;
          return this;
      }


      public Builder setMessage(CharSequence message) {
          P.mMessage = message;
          return this;
      }

      public Builder setIcon(int iconId) {
          P.mIconId = iconId;
          return this;
      }

      public Builder setPositiveButton(CharSequence text, final OnClickListener listener) {
          P.mPositiveButtonText = text;
          P.mPositiveButtonListener = listener;
          return this;
      }


      public Builder setView(View view) {
          P.mView = view;
          P.mViewSpacingSpecified = false;
          return this;
      }

      // 3 : 构建AlertDialog, 传递参数
      public AlertDialog create() {
          // 调用new AlertDialog构造对象, 并且将参数传递个体AlertDialog 
          final AlertDialog dialog = new AlertDialog(P.mContext, mTheme, false);
          // 5 : 将P中的参数应用的dialog中的mAlert对象中
          P.apply(dialog.mAlert);
          dialog.setCancelable(P.mCancelable);
          if (P.mCancelable) {
              dialog.setCanceledOnTouchOutside(true);
          }
          dialog.setOnCancelListener(P.mOnCancelListener);
          if (P.mOnKeyListener != null) {
              dialog.setOnKeyListener(P.mOnKeyListener);
          }
          return dialog;
      }
  }

}
public void apply(AlertController dialog) {
      if (mCustomTitleView != null) {
          dialog.setCustomTitle(mCustomTitleView);
      } else {
          if (mTitle != null) {
              dialog.setTitle(mTitle);
          }
          if (mIcon != null) {
              dialog.setIcon(mIcon);
          }
          if (mIconId >= 0) {
              dialog.setIcon(mIconId);
          }
          if (mIconAttrId > 0) {
              dialog.setIcon(dialog.getIconAttributeResId(mIconAttrId));
          }
      }
      if (mMessage != null) {
          dialog.setMessage(mMessage);
      }
      if (mPositiveButtonText != null) {
          dialog.setButton(DialogInterface.BUTTON_POSITIVE, mPositiveButtonText,
                  mPositiveButtonListener, null);
      }
      if (mNegativeButtonText != null) {
          dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText,
                  mNegativeButtonListener, null);
      }
      if (mNeutralButtonText != null) {
          dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText,
                  mNeutralButtonListener, null);
      }
      if (mForceInverseBackground) {
          dialog.setInverseBackgroundForced(true);
      }
      // For a list, the client can either supply an array of items or an
      // adapter or a cursor
      if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
          createListView(dialog);
      }
      if (mView != null) {
          if (mViewSpacingSpecified) {
              dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
                      mViewSpacingBottom);
          } else {
              dialog.setView(mView);
          }
      }
  }

相关文章

网友评论

    本文标题:设计模式-builder(建造者模式)

    本文链接:https://www.haomeiwen.com/subject/pjitvhtx.html