java-策列模式以及实际用法

本文详细介绍了策略模式,包括其在Java中的应用步骤,以及两种不同的实现方式:通过接口定义加减乘除操作,并根据参数选择不同实现类;通过策略配置类动态选择策略。
摘要由CSDN通过智能技术生成

一,策略模式

在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。

步骤 1
创建一个接口。

Strategy.java
public interface Strategy {
   public int doOperation(int num1, int num2);
}

步骤 2
创建实现接口的实体类。

OperationAdd.java
public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 + num2;
   }
}
OperationSubtract.java
public class OperationSubtract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}
OperationMultiply.java
public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}

步骤 3
创建 Context 类。

public class Context {
   private Strategy strategy;
 
   public Context(Strategy strategy){
      this.strategy = strategy;
   }
 
   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

步骤 4
使用 Context 来查看当它改变策略 Strategy 时的行为变化。

public class StrategyPatternDemo {
   public static void main(String[] args) {
      Context context = new Context(new OperationAdd());    
      System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
 
      context = new Context(new OperationSubtract());      
      System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
 
      context = new Context(new OperationMultiply());    
      System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
   }
}

步骤 5
执行程序,输出结果:

10 + 5 = 15
10 - 5 = 5
10 * 5 = 50

二,策略模式的其它实现方式(一);

1,定义一个需要被实现加减乘除的接口;

public interface IOperationService {

    int doOperation(int num1, int num2);
}

2,在写两个实现IOperationService接口的实现类;

/**
 * 加法实现类
 */
@Service()
public class OperationAddImpl implements IOperationService {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}
/**
 * 减法实现类
 */
@Service
public class OperationSubtractImpl implements IOperationService {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

3,定义一个常量类,主要作用是根据前端的指定的入参找到bean id

public class  OperationEnumConstant {

    public static String ADD_BEAN_ID = "operationAddImpl";

    public static String SUB_BEAN_ID = "OperationSubtractImpl";

    public enum OperationEnum{

        ADD("add",OperationEnumConstant.ADD_BEAN_ID,"加法业务"),

        SUB("sub",OperationEnumConstant.SUB_BEAN_ID,"减法业务");


        private String code;

        private String beanId;

        private String desc;

        OperationEnum(String code, String beanId, String desc) {
            this.code =code;
            this.beanId =beanId;
            this.desc= desc;
        }

        public String getCode(){
            return this.code;
        }

        public String getBeanId(){
            return this.beanId;
        }


        public static OperationEnum getEnumByCode(String code){
            for(OperationEnum num : OperationEnum.values()){
                if(code.equals(num.getCode())){
                    return num;
                }
            }
            return null;
        }

    }

}
4,定义控制层,控制根据入参找到指定实现类


@RunWith(SpringRunner.class)
@SpringBootTest
public class OperationImpl {

    @Autowired
    private Map<String, IOperationService> operationService;

    @Test
    public void Operation(){

        String type = "add";  //模拟前端的入参参数

        int a = 1;

        int b = 2;

        OperationEnumConstant.OperationEnum enumByCode = OperationEnumConstant.OperationEnum.getEnumByCode(type);

        IOperationService operationService = this.operationService.get(enumByCode.getBeanId());

        int i = operationService.doOperation(a, b);

        System.out.println(i);  //输出结果  3

    }
}

三,策略模式的其它实现方式(二);

1,定义一个需要被实现加减乘除的接口;

public interface IOperationService {

    int doOperation(int num1, int num2);

    Boolean isMatch(String type);

}

2,实现IOperationService接口;

/**
 * 加法实现类
 */
@Service()
public class OperationAddImpl implements IOperationService {
    
    private static String ADD_SERVICE = "add";

    @Override
    public Boolean isMatch(String type) {
        return ADD_SERVICE.equals(type);
    }

    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}
/**
 * 减法实现类
 */
@Service
public class OperationSubtractImpl implements IOperationService {
    
    private static String ADD_SERVICE = "sub";

    @Override
    public Boolean isMatch(String type) {
        return ADD_SERVICE.equals(type);
    }

    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }

}

3,定义策略配置类;

@Component
public class OperationConfig {

    private static List<IOperationService> arr =  new ArrayList<>();

    @Autowired
    public void setOperationHanld(List<IOperationService> serviceList){
        for (IOperationService service : serviceList) {
            arr.add(service);
        }
    }

    public static IOperationService getOperationService(String type){
        for (IOperationService service : arr) {
            if(service.isMatch(type)){
                return service;
            }
        }
        return null;//当没匹配到你想要的实现的时候,这里你也可写个默认的实现类
    }
}

4,控制层编写,根据入参找到实现类

@Test
public void Operation2(){

     String type = "sub"; //模拟前端入参

     int a = 5;

     int b = 2;

     IOperationService operationService = OperationConfig.getOperationService(type);

     int i = operationService.doOperation(a, b);

     System.out.println(i); //输出结果 3
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值