设计模式(1)--策略模式

一、前言

为什么要学习设计模式?首先学习设计模式不能死记代码,要理解表层代码后蕴含的设计思想。在平时写业务代码的时候也会追求一种代码之间松耦合的状态,有时候和设计模式中的思想有一定的共通之处。但是不去刻意学习设计模式和仔细研究过设计模式的代码就像杂牌军遇到正规军,在代码的执行效率、耦合性、内聚性、后期的可维护拓展性必定无法同日而语。本次就记录一下我学习策略模式的过程以及之后的心得体会。

二、策略模式

(1)概念介绍

定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。

(2)策略模式的结构

(3)举例

 1 package Stratge;
 2 /**
 3  * 策略模式父类接口
 4  * @author sunj
 5  *
 6  */
 7 public interface IntStratge {
 8     public int doOpertiation(int num1, int num2);
 9 }
10 
11 package Stratge;
12 /**
13  * 子类实现父类接口并重写父类方法
14  * @author sunj
15  *
16  */
17 public class OperationAdd implements IntStratge{
18 
19     @Override
20     public int doOpertiation(int num1, int num2) {
21         return num1 + num2;
22     }
23 
24 }
25 
26 package Stratge;
27 
28 public class OperationSub implements IntStratge{
29 
30     @Override
31     public int doOpertiation(int num1, int num2) {
32         return num1 - num2;
33     }
34 
35 }
36 
37 package Stratge;
38 /**
39  * 策略模式的具体实现,利用java的多态特性实现代码之间的松耦合。
40  * @author sunj
41  *
42  */
43 public class Context {
44     private IntStratge intStratge;
45     
46     public Context (IntStratge intStratge){
47         this.intStratge = intStratge;
48     }
49     
50     public int excStratge(int num1, int num2){
51         return intStratge.doOpertiation(num1, num2);
52     }
53     
54     public static void main(String[] args) {
55         Context context = new Context(new OperationAdd());
56         context.excStratge(1, 1);
57     }
58 }

三、总结

从最后的context类可以看出策略模式充分利用java中的多态特性隐藏了之类的具体实现方法,使代码看起来层次更加分明,理解起来也更容易一些。我曾经参加过国家农业部的一个农业综合开发项目,项目中分为几块大类型:土地、产业化、其他。这三种类型大部分特性相同,也有小部分个性化特征,完全可以采取策略模式进行分层编写,当时着急完成任务导致代码过于臃肿给后期维护拓展带来了很大的麻烦。

从上面的总结可以看出策略模式达到了松耦合的目的,提高了代码的内聚性。

猜你喜欢

转载自www.cnblogs.com/sjjava/p/9542174.html