建造者模式會讓你的代碼整潔品抽,工廠化。
private void openFilePicker() {
new MaterialFilePicker()
.withSupportFragment(this)
.withRequestCode(1)
.withFilter(Pattern.compile(".*\\.txt$")) // Filtering files and directories by file name using regexp
.withFilterDirectories(false) // Set directories filterable (false by default)
.withHiddenFiles(true) // Show hidden files and folders
.withRootPath(Environment.getRootDirectory().getPath())
.start();
}
這就是建造者模式基本式樣
那么在 MaterialFilePicker 類里面。一些類是這樣的方法就是添加條件
public MaterialFilePicker withSelectType(int selectType) {
mSelectType = selectType;
return this;
}
.....
而往往最后一個 start()方法則是執(zhí)行關鍵。
public void start() {
if (mActivity == null && mFragment == null && mSupportFragment == null) {
throw new RuntimeException("You must pass Activity/Fragment by calling withActivity/withFragment/withSupportFragment method");
} if (mRequestCode == null) {
throw new RuntimeException("You must pass request code by calling withRequestCode method");
} Intent intent = getIntent();
if (mActivity != null) {
mActivity.startActivityForResult(intent, mRequestCode);
} else if (mFragment != null) {
mFragment.startActivityForResult(intent, mRequestCode);
} else {
mSupportFragment.startActivityForResult(intent, mRequestCode);
}
}