Java中策略模式代码分享
下文笔者将采用示例的方式讲述策略模式的应用,如下所示
实现思路: 1.定义一个策略接口 为接口编写多种不同的策略实现类 2.编写主实现类 并为主方法中定义参数为策略 3.当我们使用时,传入相应的策略方法 即可实现不同的效果 策略模式的要点: 利用多态的特性 参数中使用策略接口,使用时传入具体的实现类 采用这种模式,达到不同的运行效果 其本质是多态的一种表现形式例:
策略模式的示例分享
public interface Strategy{ public int calculate(int a, int b); }
public class AddStrategy implements Strategy{ public int calculate(int a, int b){ return a + b; } } public class DivideStrategy implements Strategy{ public int calculate(int a, int b){ return a / b; } } public class MultiplyStrategy implements Strategy{ public int calculate(int a, int b){ return a * b; } } public class SubtractStrategy implements Strategy{ public int calculate(int a, int b){ return a - b; } }
public class Environment{ private Strategy strategy; public Environment(Strategy strategy){ this.strategy = strategy; } public Strategy getStrategy(){ return strategy; } public void setStrategy(Strategy strategy){ this.strategy = strategy; } public int calculate(int a ,int b){ return strategy.calculate(a , b); } }
public class Client{ public static void main(String[] args){ AddStrategy addStrategy = new AddStrategy(); Environment environment = new Environment(addStrategy); System.out.println(environment.calculate(88, 99)); SubtractStrategy subtractStrategy = new SubtractStrategy(); environment.setStrategy(subtractStrategy); System.out.println(environment.calculate(66, 77)); MultiplyStrategy multiplyStrategy = new MultiplyStrategy(); environment.setStrategy(multiplyStrategy); System.out.println(environment.calculate(66, 77)); DivideStrategy divideStrategy = new DivideStrategy(); environment.setStrategy(divideStrategy); System.out.println(environment.calculate(88, 99)); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。