策略模式

 

             首先你需要一个接口,定义需要的行为方法,如下:

interface Strategy{
    void algorithm();
}

              然后你需要几个实现了这个接口的实现类,如下

public class Strategy1 implements Strategy{
    void algorithm(){
         System.out.println("this is the Strategy1 algorithm");   
    }
}

public class Strategy2 implements Strategy{
    void algorithm(){
         System.out.println("this is the Strategy2 algorithm");   
    }
}

           最后在你需要这个实现类的客户端类定义这个接口的变量,在构造函数或者set方法中传进来具体的实现类复制给接口变量

           接着定义客户端类的行为方法,这里面只需要调用接口的行为就可以了。

public class Context{
     private Strategy strategy;
     public Context(Strategy strategy){
                this.strategy=strategy;
    }
     public void operation(){
         this.strategy.algorithm();
    }
}

          至此,完成了策略模式最基本的实现形式,上一下官方图

 

策略模式的应用场景主要在于替换掉多if else的场景。结合反射+工厂模式或者map+工厂模式可以通过关键字应用对应的策略类从而避免if else使用,其实就是将选择推迟到了map中的查询和反射。

               

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值