You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository has been archived by the owner on Feb 2, 2019. It is now read-only.
public class Calculator{
// 加符号
private final static String ADD_SYMBOL = "+";
// 减符号
private final static String SUB_SYMBOL = "-";
// 执行
public int exec(int a, int b, String symbol){
int result = 0;
if(symbol.equals(ADD_SYMBOL)){ // 比较
result = this.add(a,b);
}else if(symbol.equals(SUB_SYMBOL)){
result = this.sub(a,b);
}
}
// 加法
public int add(int a, int b){
return a + b;
}
// 减法
public int sub(int a, int b){
return a - b;
}
}
书写场景类
public class Client{
public static void main(String[] args){
// 获取输入
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
// 生成运算器
Calculator calculator = new Calculator();
calculator.exec(a,b);
}
}
引入策略模式
即,将原先的加减法进行拆分
引入策略模式
protected interface Calculator{
public int exec(int a, int b);
}
书写具体策略
public class Add implements Calculator{
// 加法
@Overrider
public int exec(int a, int b){
return a + b;
}
}
书写减法运算
public class Sub implements Calculator{
// 减法
public int exec(int a, int b){
return a - b;
}
}
why?为什么要进行封装,因为保证可以随时的增加具体的策略,所以需要一个上下文。
public class Context{
private Calculator cal = null;
// 通过构造函数注入
public Context(Calculator _cal){
this.cal = _cal; // 完成指向
}
// 执行
public int exec(int a, int b){
return this.cal.exec(a,b);
}
}
场景
public class Client{
// 加
public final static String ADD_SYMBOL = "+";
// 减
public final static String SUB_SYMBOL = "-";
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
String symbol = args[1];
int b = Integer.parseInt(args[2]);
// 初始化上下文
Context context = null;
// 选择策略
if(symbol.equals(ADD_SYMBOL)){
context = new Context(new Add());
}else if(symbol.equals(SUB_SYMBOL)){
context = new COntext(new SUb());
}
// 结果
context.exec(a,b);
}
}
使用枚举
public enum Calculator{
// 枚举成员
// 加法枚举
ADD("+"){
public int exec(int a, int b){
return a + b;
}
}
// 减法枚举
SUB("-"){
public int exec(int a, int b){
return a - b;
}
}
// 定义类型
String value = "";
// 构造
private Calculator(String _value){
this.value = _value;
}
// get
public String getValue(){
return this.value;
}
// 预留扩展
public abstract int exec(int a. int b);
}
最后书写场景
public class Client{
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
String symbol = args[1];
int b = Integer.parseInt(args[2]);
Calculator.ADD.exec(a, b);
}
}
设计模式-策略模式
以计算器为栗
最直接加减法
书写场景类
引入策略模式
即,将原先的加减法进行拆分
引入策略模式
书写具体策略
书写减法运算
why?为什么要进行封装,因为保证可以随时的增加具体的策略,所以需要一个上下文。
场景
使用枚举
最后书写场景
总结
将原先耦合的if进行拆分成类,然后使用的时候注入类即可。或者使用枚举类型,如果需要增加,需要实现抽象方法。
应用
动画的实现,将各种缓动函数,书写为策略模式,然后使用的时候,将类注入即可。
表单校验,同样可以将各种校验进行解耦,使用的时候注入即可。
The text was updated successfully, but these errors were encountered: