绪论
其实很早以前就看过一些关于设计模式的文章,知道这个很重要,为此还写了一些demo,但是在实际开发过程中基本没有使用过。原因:不习惯,不记得,其实更多的是不明白什么情况下可以使用。所以导致自己的代码又臭又长,还会重复的造一些轮子,使代码看起来毫无亮点。
这次学习设计模式,更多的是分析理解,思考以往编程中哪些地方可以用到这些模式,从而可以使以后的自己在开发相同模块时可以使用。
理解
- 一个类的行为可以在运行时动态的更改。
- 在多种行为相似的情况下,可以减少if…else…的复杂度。
- 需要实现同一个接口。
- 参考java.util.Comparator的compare方法。
代码
方式一:
定义接口
public interface Strategy {
int operation(int a, int b);
}
实现加
public class StrategyAdd implements Strategy {
@Override
public int operation(int a, int b) {
return a + b;
}
}
实现减
public class StrategySubtract implements Strategy {
@Override
public int operation(int a, int b) {
return a - b;
}
}
计算管理
public class Calculate {
private Strategy strategy;
public Calculate(Strategy strategy) {
this.strategy = strategy;
}
public int operation(int a, int b) {
return strategy.operation(a, b);
}
}
主方法
public class Main {
public static void main(String[] args) {
Calculate calculate = new Calculate(new StrategyAdd());
System.out.println("1 + 2 = " + calculate.operation(1, 2));
calculate = new Calculate(new StrategySubtract());
System.out.println("1 - 2 = " + calculate.operation(1, 2));
}
}
方式二:
保留Strategy与其实现,重写Calculate。 注意:最好在Strategy加上@FunctionalInterface注解。
public class Calculate {
public int operation(int a, int b, Strategy strategy) {
return strategy.operation(a, b);
}
}
主方法
public class Main {
public static void main(String[] args) {
Calculate calculate = new Calculate();
System.out.println("4 + 2 = " + calculate.operation(4, 2, new StrategyAdd()));
System.out.println("4 - 2 = " + calculate.operation(4, 2, new StrategySubtract()));
// 可以用匿名内部类重新定义实现
System.out.println("4 * 2 = " + calculate.operation(4, 2, new Strategy() {
@Override
public int operation(int a, int b) {
return a * b;
}
}));
// java8 Lambda
System.out.println("4 / 2 = " + calculate.operation(4, 2, (a, b) -> a / b));
}
}
结果
方式一结果:
方式二结果:
(若有什么错误,请留言指正,3Q)