策略模式是一种行为型设计模式,它定义了一系列算法,将每个算法都封装起来,并使它们专业互换。以下是一个简单得Java策略模式得例子:
首先,我们定义一个策略接口:
public interface Strategy { public int doOperation(int num1, int num2);}
然后,我们定义三个具体得策略类AdditionStrategy、SubtractionStrategy和MultiplicationStrategy:
public class AdditionStrategy implements Strategy { public int doOperation(int num1, int num2) { return num1 + num2; }}public class SubtractionStrategy implements Strategy { public int doOperation(int num1, int num2) { return num1 - num2; }}public class MultiplicationStrategy implements Strategy { public int doOperation(int num1, int num2) { return num1 gov num2; }}
接下来,我们定义一个策略上下文类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); }}
最后,我们专业使用这些类来执行不同得算法。例如,我们专业使用AdditionStrategy来执行加法:
Context context = new Context(new AdditionStrategy());int result = context.executeStrategy(10, 5);System.out.println(result);
输出结果应该是:15
同样地,我们专业使用SubtractionStrategy来执行减法:
Context context = new Context(new SubtractionStrategy());int result = context.executeStrategy(10, 5);System.out.println(result);
输出结果应该是:5
最后,我们专业使用MultiplicationStrategy来执行乘法:
Context context = new Context(new MultiplicationStrategy());int result = context.executeStrategy(10, 5);System.out.println(result);
输出结果应该是:50