java设计模式--策略模式

首先,说几条书中提到的设计原则

1.把应用中可能变化的独立出来,不要和不需要变化的代码混在一起

2.针对接口编程,而不是针对实现编程

3.多用组合,少用继承

参考连接:https://www.cnblogs.com/java-my-life/archive/2012/05/10/2491891.html

因为目的主要是自己学习,所以上面会放上比较好的文章链接

1.创建计算抽象类

public interface CalculationStrategy {
public int result(int a,int b);
}

2.实现求乘积

public class Product implements CalculationStrategy {
@Override
public int result(int a, int b) {
return a * b;
}
}

3.实现求和

public class Sum implements CalculationStrategy {
@Override
public int result(int a, int b) {
System.out.print("求和");
return a + b;
}
}

4.计算类

public class Calculation {
private CalculationStrategy calculationStrategy;

public Calculation(CalculationStrategy calculationStrategy){
this.calculationStrategy = calculationStrategy;
}

public int calculation(int a, int b){
return this.calculationStrategy.result(a,b);
}
}

5.运行

public class Client {
public static void main(String[] args) {
//选择需要的策略对象
CalculationStrategy calculationStrategy = new Sum();
//创建环境
Calculation calculation = new Calculation(calculationStrategy);
//计算
System.out.print(calculation.calculation(1,2));
}
}
posted @ 2018-11-13 23:03  leavesss  阅读(42)  评论(0编辑  收藏  举报