设计模式10--策略模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_16658263/article/details/89302505

什么是策略模式

定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

策略模式由三种角色组成

策略模式应用场景

策略模式的用意是针对一组算法或逻辑,将每一个算法或逻辑封装到具有共同接口的独立的类中,从而使得它们之间可以相互替换。策略模式使得算法或逻辑可以在不影响到客户端的情况下发生变化。说到策略模式就不得不提及OCP(Open Closed Principle) 开闭原则,即对扩展开放,对修改关闭。策略模式的出现很好地诠释了开闭原则,有效地减少了分支语句。

 

策略模式代码

此代码通过模拟不同会员购物车打折力度不同分为三种策略,初级会员,中级会员,高级会员。

//策略模式 定义抽象方法所有支持公共接口

abstract class Strategy {

 

     // 算法方法

     abstract voidalgorithmInterface();

 

}

 

class StrategyA extendsStrategy {

 

     @Override

     void algorithmInterface() {

           System.out.println("算法A");

 

     }

 

}

 

class StrategyB extendsStrategy {

 

     @Override

     void algorithmInterface() {

           System.out.println("算法B");

 

     }

 

}

 

class StrategyC extendsStrategy {

 

     @Override

     void algorithmInterface() {

           System.out.println("算法C");

 

     }

 

}

// 使用上下文维护算法策略

 

class Context {

 

     Strategy strategy;

 

     public Context(Strategy strategy) {

           this.strategy = strategy;

     }

 

     public voidalgorithmInterface() {

           strategy.algorithmInterface();

     }

 

}

 

class ClientTestStrategy {

     public static voidmain(String[] args) {

           Context context;

           context = newContext(new StrategyA());

           context.algorithmInterface();

           context = newContext(new StrategyB());

           context.algorithmInterface();

           context = newContext(new StrategyC());

           context.algorithmInterface();

 

     }

}

猜你喜欢

转载自blog.csdn.net/sinat_16658263/article/details/89302505
今日推荐