package com.example.designmodel;
/**
* 抽象策略模式
*/
public class StrategyModel {
/**
* 定义抽象策略
*/
public interface Strategy{
void calc(int a, int b);
}
/**
* 定义具体减法策略
*/
public class ReduceStrategy implements Strategy{
@Override
public void calc(int a, int b) {
System.out.println(a-b);
}
}
/**
* 定义具体加法策略
*/
public class AddStrategy implements Strategy{
@Override
public void calc(int a, int b) {
System.out.println(a+b);
}
}
/**
* 定义环境角色,类似于TreeSet,解耦策略执行模式
*/
public class Environment{
private Strategy strategy;
Environment(Strategy strategy){
this.strategy = strategy;
}
public void calcExe(int a, int b){
this.strategy.calc(a, b);
}
}
public static void main(String[] args){
StrategyModel strategyModel = new StrategyModel();
//创建具体策略实例
AddStrategy addStrategy = strategyModel.new AddStrategy();
//给程序安装加法策略
Environment environment = strategyModel.new Environment(addStrategy);
//执行
environment.calcExe(5,7);
}
}
策略模式
最新推荐文章于 2024-11-10 14:59:24 发布