- package strategy;
-
- public class First {
- public static void main(String[] args) {
- Strategy strategy;
- String a = "";
- Context context = null;
- context = new Context(new ConcreteStrategyA());
- context.AlgorithmInterface();
- context = new Context(new ConcreteStrategyB());
- context.AlgorithmInterface();
- }
- }
- /**
- * 上下文类 用于创建
- */
- class Context {
- Strategy strategy;
- //获取
- public Context(Strategy strategy) {
- this.strategy = strategy;
- }
- //计算方式执行
- public void AlgorithmInterface() {
- this.strategy.AlgorithmInterface();
- }
- }
- /**
- * 算法类
- */
- abstract class Strategy {
- //计算方式
- public abstract void AlgorithmInterface();
- }
- /**
- * 算法A
- */
- class ConcreteStrategyA extends Strategy {
- //计算方式
- public void AlgorithmInterface() {
- //算法A实现
- }
- }
- /**
- * 算法B
- */
- class ConcreteStrategyB extends Strategy {
- //计算方式
- public void AlgorithmInterface() {
- //算法B实现
- }
- }
- package strategy;
-
- public class First {
- public static void main(String[] args) {
- Strategy strategy;
- String a = "";
- Context context = new Context(a);
- context.AlgorithmInterface();
- }
- }
- /**
- * 上下文类 用于创建
- */
- class Context {
- Strategy strategy;
- //获取
- public Context(String a) {
- switch (a) {
- case "1":
- strategy = new ConcreteStrategyA();
- break;
- case "2":
- strategy = new ConcreteStrategyB();
- break;
- }
- }
- //计算方式执行
- public void AlgorithmInterface() {
- this.strategy.AlgorithmInterface();
- }
- }
- /**
- * 算法类
- */
- abstract class Strategy {
- //计算方式
- public abstract void AlgorithmInterface();
- }
- /**
- * 算法A
- */
- class ConcreteStrategyA extends Strategy {
- //计算方式
- public void AlgorithmInterface() {
- //算法A实现
- }
- }
- /**
- * 算法B
- */
- class ConcreteStrategyB extends Strategy {
- //计算方式
- public void AlgorithmInterface() {
- //算法B实现
- }
- }