Android中的工厂模式,目的就是减少if-else和switch-case的出现,梳理代码的条理,使逻辑更加清晰,下面直接上代码:
1.首先新建一个接口,用来监听我们的操作
public interface StrategyListenter {
/**
*
* @param context 上下文
* @param result 需要操作的数据
* @param isHandled 判断是否进行下一步操作
*/
void execute(Context context, int result, boolean[] isHandled);
}
2.重点来了,策略工厂类
public class StrategFactory {
private List<StrategyListenter> list = new ArrayList<>();
private static StrategFactory strategFactory = new StrategFactory();
/**
* 单列模式
*
* @return
*/
public static StrategFactory init() {
return strategFactory;
}
/**
* 添加具体操作的类
*
* @param listenter
* @return
*/
public StrategFactory add(StrategyListenter listenter) {
if (listenter != null) {
list.add(listenter);
}
return this;
}
/**
* 调用接口进行操作
*
* @param context
* @param result 可根据实际情况进行修改
*/
public void Scheduled(Context context, int result) {
boolean[] isHandled = {false};
for (StrategyListenter listenter : this.list) {
if (isHandled[0]) {
return;
}
listenter.execute(context, result, isHandled);
}
}
}
3.在Application中声明
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
StrategFactory strategFactory = StrategFactory.init();
strategFactory.add(new NumberOne());
strategFactory.add(new NumberTwo());
strategFactory.add(new NumberThree());
strategFactory.add(new NumberFour());
}
}
4.具体的操作类,在这里面可以执行我们想要的操作
public class NumberOne implements StrategyListenter {
@Override
public void execute(Context context, int result, boolean[] isHandled) {
if (result >= 0 && result < 60) {
DilaogHelper.getDilaog(context, "提示信息", "不及格");
isHandled[0] = false;
}
}
}
5.最后在MianActivity中应用
public class MainActivity extends AppCompatActivity {
private EditText ed_input;
private Button btn_submit;
private int strInputNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_input = (EditText) findViewById(R.id.ed_input);
btn_submit = (Button) findViewById(R.id.btn_submit);
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
strInputNumber = Integer.valueOf(ed_input.getText().toString());
StrategFactory.init().Scheduled(MainActivity.this, strInputNumber);
}
});
}
}
6.自己封装的一个对话框帮助类
public class DilaogHelper {
public static void getDilaog(Context context, String title, String message){
new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton("确定", null)
.show();
}
}
附:代码资源下载地址:
http://download.csdn.net/download/qq_32376365/9942966
}