设计模式之策略模式

1 概述

    策略模式(Strategy Patern),是把针对同一件事情的不同的算法分别封装起来,并且相互之间可以替换。这种模式的使用需要以下三种角色:

(1)环境角色:应用不同的策略来达到完成某件事情的目的;

(2)抽象策略角色:通常由接口或者抽象类实现,所有的具体角色都继承此抽象;

(3)具体策略角色:具体的算法实现;

2 示例

    相对来说,例子还是挺多的,比如淘宝搜索的时候,是按照卖出量排序还是价格排序还是好评度排序等等。

    前面的几种模式都是拿手机做例子,那还是继续手机做例子吧。

    现在的智能手机基本上都是大屏幕,看着花里胡哨的很爽。流行的手机操作系统都支持换屏幕主题的功能。不同的Theme有着不同的背景图、图标、字体。用户还能自定义特殊癖好的主题。

    首先来个接口,所有的手机主题都必须实现此接口

 1 package org.scott.strategy;
 2 /** 
 3  * @author Scott
 4  * @date 2013年12月22日 
 5  * @description
 6  */
 7 public interface Theme {
 8     public void backGround();
 9     public void fontStyle();
10     public void smsRing();
11 }

    接口中定义了三个方法,分别是背景图片、字体类型、通知铃声。有了抽象策略角色,下面就实现两个具体的主题策略

 1 package org.scott.strategy;
 2 /** 
 3  * @author Scott
 4  * @date 2013年12月22日 
 5  * @description
 6  */
 7 public class ClassficTheme implements Theme {
 8 
 9     @Override
10     public void backGround() {
11         System.out.println("Back ground image is: 水墨中国.jpeg.");
12     }
13 
14     @Override
15     public void fontStyle() {
16         System.out.println("Font style is: 正楷.");
17     }
18 
19     @Override
20     public void smsRing() {
21         System.out.println("The sms ring is: 春江花月夜");
22     }
23 
24 }

    再来个现代风格的主题:

 1 package org.scott.strategy;
 2 /** 
 3  * @author Scott
 4  * @date 2013年12月22日 
 5  * @description
 6  */
 7 public class ModernTheme implements Theme {
 8 
 9     @Override
10     public void backGround() {
11         System.out.println("Back ground image is: 奇幻星空.jpeg.");
12     }
13 
14     @Override
15     public void fontStyle() {
16         System.out.println("Font style is: 静蕾体.");
17     }
18 
19     @Override
20     public void smsRing() {
21         System.out.println("The sms ring is: Nohthing In The World.");
22     }
23 
24 }

    有了抽象策略和具体策略,还差个Context角色

 1 package org.scott.strategy;
 2 /** 
 3  * @author Scott
 4  * @date 2013年12月22日 
 5  * @description
 6  */
 7 public class Context {
 8     private Theme theme;
 9     
10     public void setTheme(Theme theme) {
11         this.theme = theme;
12     }
13 
14     public void getTheme(){
15         theme.backGround();
16         theme.fontStyle();
17         theme.smsRing();
18     }
19 }

    我们来个手机设定个Theme吧,看看我们的客户端代码:

 1 package org.scott.strategy;
 2 /** 
 3  * @author Scott
 4  * @date 2013年12月22日 
 5  * @description
 6  */
 7 public class StrategyClient {
 8 
 9     public static void main(String[] args) {
10         Context theme = new Context();
11         theme.setTheme(new ClassficTheme());
12         theme.getTheme();
13     }
14 }

    执行结果呢?

Back ground image is: 水墨中国.jpeg.
Font style is: 正楷.
The sms ring is: 春江花月夜

    

3 小结

    策略模式一个很大的特点就是各个策略算法的平等性。对于一系列具体的策略算法,大家的地位是完全一样的,正因为这个平等性,才能实现算法之间可以相互替换。所有的策略算法在实现上也是相互独立的,相互之间没有依赖。

    并且,在运行期间,策略模式在每一个时刻只能使用一个具体的策略实现对象,虽然可以动态地在不同的策略实现中切换,但是同时只能使用一个。就像我们的例子,只能使用一个主题,这个可以理解,你只有一个手机,一个屏幕~

    最后上个经典的类图吧(源自网络):

原文地址:https://www.cnblogs.com/Scott007/p/3486577.html