package com.leitao.demo.design;
/**
* 策略
* @Description: TODO
* @Author LeiTao
* @Date 2023/5/4
* @Version V1.0
**/
public class StrategyPattern {
public static void main(String[] args) {
Strategy addStrategy = new AddStrategy();
Strategy subStrategy = new SubStrategy();
Strategy rideStrategy = new RideStrategy();
Context context = new Context(addStrategy);
context.Operation(12,3);
context = new Context(subStrategy);
context.Operation(12,3);
context = new Context(rideStrategy);
context.Operation(12,3);
}
}
class Context{
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void Operation(int a,int b){
strategy.twoNumberOperation(a,b);
}
}
interface Strategy {
void twoNumberOperation(int a,int b);
}
class AddStrategy implements Strategy {
@Override
public void twoNumberOperation(int a, int b) {
System.out.println("两数相加:" + (a + b));
}
}
class SubStrategy implements Strategy {
@Override
public void twoNumberOperation(int a, int b) {
System.out.println("两数相减:" + (a - b));
}
}
class RideStrategy implements Strategy {
@Override
public void twoNumberOperation(int a, int b) {
System.out.println("两数相乘:" + (a * b));
}
}