---
title: "[转]23种设计模式全解析-关系模式"
author: "vineet"
date: "2014-05-05T23:40:37Z"
tags: []
categories: ["编程语言"]
slug: "23"
draft: false
lastmod: "2014-05-05T23:40:37Z"
id: 2061875
url: "https://vineet.iteye.com/blog/2061875"
---

## **C、关系模式（11种）**

先来张图，看看这11中模式的关系：

第一类：通过父类与子类的关系进行实现。

第二类：两个类之间。

第三类：类的状态。

第四类：通过中间类

![](http://dl.iteye.com/upload/attachment/0083/1211/5e2feb58-4170-3c07-a370-ed99bdcab223.jpg)

 

## []()父类与子类关系

### []()**13、策略模式（strategy）**

策略模式定义了一系列算法，并将每个算法封装起来，使他们可以相互替换，且算法的变化不会影响到使用算法的客户。需要设计一个接口，为一系列实现类提供统一的方法，多个实现类实现该接口，设计一个抽象类（可有可无，属于辅助类），提供辅助函数，关系图如下：

![](http://dl.iteye.com/upload/attachment/0083/1213/2319a2c3-7ebd-3ee3-b389-1548074ea9c6.jpg)

图中ICalculator提供同意的方法，  
AbstractCalculator是辅助类，提供辅助方法，接下来，依次实现下每个类：

首先统一接口：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **interface** ICalculator {
2. **public** **int** calculate(String exp);
3. }

辅助类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **abstract** **class** AbstractCalculator {
2. **public** **int**\[] split(String exp,String opt){
3. String array\[] = exp.split(opt);
4. **int** arrayInt\[] = **new** **int**\[2];
5. arrayInt\[0] = Integer.parseInt(array\[0]);
6. arrayInt\[1] = Integer.parseInt(array\[1]);
7. **return** arrayInt;
8. }
9. }

三个实现类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Plus **extends** AbstractCalculator **implements** ICalculator {
2. @Override
3. **public** **int** calculate(String exp) {
4. **int** arrayInt\[] = split(exp,"\\\\+");
5. **return** arrayInt\[0]+arrayInt\[1];
6. }
7. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Minus **extends** AbstractCalculator **implements** ICalculator {
2. @Override
3. **public** **int** calculate(String exp) {
4. **int** arrayInt\[] = split(exp,"-");
5. **return** arrayInt\[0]-arrayInt\[1];
6. }
7. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Multiply **extends** AbstractCalculator **implements** ICalculator {
2. @Override
3. **public** **int** calculate(String exp) {
4. **int** arrayInt\[] = split(exp,"\\\\\*");
5. **return** arrayInt\[0]\*arrayInt\[1];
6. }
7. }

简单的测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** StrategyTest {
2. **public** **static** **void** main(String\[] args) {
3. String exp = "2+8";
4. ICalculator cal = **new** Plus();
5. **int** result = cal.calculate(exp);
6. System.out.println(result);
7. }
8. }

输出：10

策略模式的决定权在用户，系统本身提供不同算法的实现，新增或者删除算法，对各种算法做封装。因此，策略模式多用在算法决策系统中，外部用户只需要决定用哪个算法即可。

 

### []()**14、模板方法模式（Template Method）**

解释一下模板方法模式，就是指：一个抽象类中，有一个主方法，再定义1...n个方法，可以是抽象的，也可以是实际的方法，定义一个类，继承该抽象类，重写抽象方法，通过调用抽象类，实现对子类的调用，先看个关系图：

![](http://dl.iteye.com/upload/attachment/0083/1215/c3d57775-ddf9-302b-9dfe-c65967518d3c.jpg)

就是在AbstractCalculator类中定义一个主方法calculate，calculate()调用spilt()等，Plus和Minus分别继承AbstractCalculator类，通过对AbstractCalculator的调用实现对子类的调用，看下面的例子：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **abstract** **class** AbstractCalculator {
02. /\*主方法，实现对本类其它方法的调用\*/
03. **public** **final** **int** calculate(String exp,String opt){
04. **int** array\[] = split(exp,opt);
05. **return** calculate(array\[0],array\[1]);
06. }
07. /\*被子类重写的方法\*/
08. **abstract** **public** **int** calculate(**int** num1,**int** num2);
09. **public** **int**\[] split(String exp,String opt){
10. String array\[] = exp.split(opt);
11. **int** arrayInt\[] = **new** **int**\[2];
12. arrayInt\[0] = Integer.parseInt(array\[0]);
13. arrayInt\[1] = Integer.parseInt(array\[1]);
14. **return** arrayInt;
15. }
16. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Plus **extends** AbstractCalculator {
2. @Override
3. **public** **int** calculate(**int** num1,**int** num2) {
4. **return** num1 + num2;
5. }
6. }

测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** StrategyTest {
2. **public** **static** **void** main(String\[] args) {
3. String exp = "8+8";
4. AbstractCalculator cal = **new** Plus();
5. **int** result = cal.calculate(exp, "\\\\+");
6. System.out.println(result);
7. }
8. }

我跟踪下这个小程序的执行过程：首先将exp和"\\\\+"做参数，调用AbstractCalculator类里的calculate(String,String)方法，在calculate(String,String)里调用同类的split()，之后再调用calculate(int ,int)方法，从这个方法进入到子类中，执行完return num1 + num2后，将值返回到AbstractCalculator类，赋给result，打印出来。正好验证了我们开头的思路。

 

## []()类之间的关系

### []()**15、观察者模式（Observer）**

包括这个模式在内的接下来的四个模式，都是类和类之间的关系，不涉及到继承，学的时候应该 记得归纳，记得本文最开始的那个图。观察者模式很好理解，类似于邮件订阅和RSS订阅，当我们浏览一些博客或wiki时，经常会看到RSS图标，就这的意思是，当你订阅了该文章，如果后续有更新，会及时通知你。其实，简单来讲就一句话：当一个对象变化时，其它依赖该对象的对象都会收到通知，并且随着变化！对象之间是一种一对多的关系。先来看看关系图：

![](http://dl.iteye.com/upload/attachment/0083/1233/d588525c-fbad-3040-971c-69b2716c67a4.jpg)

我解释下这些类的作用：MySubject类就是我们的主对象，Observer1和Observer2是依赖于MySubject的对象，当MySubject变化时，Observer1和Observer2必然变化。AbstractSubject类中定义着需要监控的对象列表，可以对其进行修改：增加或删除被监控对象，且当MySubject变化时，负责通知在列表内存在的对象。我们看实现代码：

一个Observer接口：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **interface** Observer {
2. **public** **void** update();
3. }

两个实现类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Observer1 **implements** Observer {
2. @Override
3. **public** **void** update() {
4. System.out.println("observer1 has received!");
5. }
6. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Observer2 **implements** Observer {
2. @Override
3. **public** **void** update() {
4. System.out.println("observer2 has received!");
5. }
6. }

Subject接口及实现类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **interface** Subject {
02. /\*增加观察者\*/
03. **public** **void** add(Observer observer);
04. /\*删除观察者\*/
05. **public** **void** del(Observer observer);
06. /\*通知所有的观察者\*/
07. **public** **void** notifyObservers();
08. /\*自身的操作\*/
09. **public** **void** operation();
10. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **abstract** **class** AbstractSubject **implements** Subject {
02. **private** Vector&lt;Observer&gt; vector = **new** Vector&lt;Observer&gt;();
03. @Override
04. **public** **void** add(Observer observer) {
05. vector.add(observer);
06. }
07. @Override
08. **public** **void** del(Observer observer) {
09. vector.remove(observer);
10. }
11. @Override
12. **public** **void** notifyObservers() {
13. Enumeration&lt;Observer&gt; enumo = vector.elements();
14. **while**(enumo.hasMoreElements()){
15. enumo.nextElement().update();
16. }
17. }
18. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** MySubject **extends** AbstractSubject {
2. @Override
3. **public** **void** operation() {
4. System.out.println("update self!");
5. notifyObservers();
6. }
7. }

测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** ObserverTest {
2. **public** **static** **void** main(String\[] args) {
3. Subject sub = **new** MySubject();
4. sub.add(**new** Observer1());
5. sub.add(**new** Observer2());
6. sub.operation();
7. }
8. }

输出：

update self!  
observer1 has received!  
observer2 has received!

 这些东西，其实不难，只是有些抽象，不太容易整体理解，建议读者：**根据关系图，新建项目，自己写代码（或者参考我的代码）,按照总体思路走一遍，这样才能体会它的思想，理解起来容易！**

 

 

### []()**16、迭代子模式（Iterator）**

顾名思义，迭代器模式就是顺序访问聚集中的对象，一般来说，集合中非常常见，如果对集合类比较熟悉的话，理解本模式会十分轻松。这句话包含两层意思：一是需要遍历的对象，即聚集对象，二是迭代器对象，用于对聚集对象进行遍历访问。我们看下关系图：

 ![](http://dl.iteye.com/upload/attachment/0083/1217/f7571a69-3c85-3fe1-b781-e460563a40a8.jpg)

这个思路和我们常用的一模一样，MyCollection中定义了集合的一些操作，MyIterator中定义了一系列迭代操作，且持有Collection实例，我们来看看实现代码：

两个接口：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **interface** Collection {
2. **public** Iterator iterator();
3. /\*取得集合元素\*/
4. **public** Object get(**int** i);
5. /\*取得集合大小\*/
6. **public** **int** size();
7. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **interface** Iterator {
2. //前移
3. **public** Object previous();
4. //后移
5. **public** Object next();
6. **public** **boolean** hasNext();
7. //取得第一个元素
8. **public** Object first();
9. }

两个实现：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **class** MyCollection **implements** Collection {
02. **public** String string\[] = {"A","B","C","D","E"};
03. @Override
04. **public** Iterator iterator() {
05. **return** **new** MyIterator(**this**);
06. }
07. @Override
08. **public** Object get(**int** i) {
09. **return** string\[i];
10. }
11. @Override
12. **public** **int** size() {
13. **return** string.length;
14. }
15. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **class** MyIterator **implements** Iterator {
02. **private** Collection collection;
03. **private** **int** pos = -1;
04. **public** MyIterator(Collection collection){
05. **this**.collection = collection;
06. }
07. @Override
08. **public** Object previous() {
09. **if**(pos &gt; 0){
10. pos--;
11. }
12. **return** collection.get(pos);
13. }
14. @Override
15. **public** Object next() {
16. **if**(pos&lt;collection.size()-1){
17. pos++;
18. }
19. **return** collection.get(pos);
20. }
21. @Override
22. **public** **boolean** hasNext() {
23. **if**(pos&lt;collection.size()-1){
24. **return** **true**;
25. }**else**{
26. **return** **false**;
27. }
28. }
29. @Override
30. **public** Object first() {
31. pos = 0;
32. **return** collection.get(pos);
33. }
34. }

测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Test {
2. **public** **static** **void** main(String\[] args) {
3. Collection collection = **new** MyCollection();
4. Iterator it = collection.iterator();
5. **while**(it.hasNext()){
6. System.out.println(it.next());
7. }
8. }
9. }

输出：A B C D E

此处我们貌似模拟了一个集合类的过程，感觉是不是很爽？其实JDK中各个类也都是这些基本的东西，加一些设计模式，再加一些优化放到一起的，只要我们把这些东西学会了，掌握好了，我们也可以写出自己的集合类，甚至框架！

 

 

 

### []()**17、责任链模式（Chain of Responsibility）**

接下来我们将要谈谈责任链模式，有多个对象，每个对象持有对下一个对象的引用，这样就会形成一条链，请求在这条链上传递，直到某一对象决定处理该请求。但是发出者并不清楚到底最终那个对象会处理该请求，所以，责任链模式可以实现，在隐瞒客户端的情况下，对系统进行动态的调整。先看看关系图：

 

 ![](http://dl.iteye.com/upload/attachment/0083/1219/729a82ce-0987-347c-a4f1-bf64dee59ddb.jpg)

 

Abstracthandler类提供了get和set方法，方便MyHandle类设置和修改引用对象，MyHandle类是核心，实例化后生成一系列相互持有的对象，构成一条链。

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **interface** Handler {
2. **public** **void** operator();
3. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **abstract** **class** AbstractHandler {
2. **private** Handler handler;
3. **public** Handler getHandler() {
4. **return** handler;
5. }
6. **public** **void** setHandler(Handler handler) {
7. **this**.handler = handler;
8. }
9. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **class** MyHandler **extends** AbstractHandler **implements** Handler {
02. **private** String name;
03. **public** MyHandler(String name) {
04. **this**.name = name;
05. }
06. @Override
07. **public** **void** operator() {
08. System.out.println(name+"deal!");
09. **if**(getHandler()!=**null**){
10. getHandler().operator();
11. }
12. }
13. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **class** Test {
02. **public** **static** **void** main(String\[] args) {
03. MyHandler h1 = **new** MyHandler("h1");
04. MyHandler h2 = **new** MyHandler("h2");
05. MyHandler h3 = **new** MyHandler("h3");
06. h1.setHandler(h2);
07. h2.setHandler(h3);
08. h1.operator();
09. }
10. }

输出：

h1deal!  
h2deal!  
h3deal!

此处强调一点就是，链接上的请求可以是一条链，可以是一个树，还可以是一个环，模式本身不约束这个，需要我们自己去实现，同时，在一个时刻，命令只允许由一个对象传给另一个对象，而不允许传给多个对象。

 

### []() **18、命令模式（Command）**

命令模式很好理解，举个例子，司令员下令让士兵去干件事情，从整个事情的角度来考虑，司令员的作用是，发出口令，口令经过传递，传到了士兵耳朵里，士兵去执行。这个过程好在，三者相互解耦，任何一方都不用去依赖其他人，只需要做好自己的事儿就行，司令员要的是结果，不会去关注到底士兵是怎么实现的。我们看看关系图：

![](http://dl.iteye.com/upload/attachment/0083/1239/98cda4fc-00b1-300d-a25b-63229f0f1cbd.jpg)

Invoker是调用者（司令员），Receiver是被调用者（士兵），MyCommand是命令，实现了Command接口，持有接收对象，看实现代码：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **interface** Command {
2. **public** **void** exe();
3. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

01. **public** **class** MyCommand **implements** Command {
02. **private** Receiver receiver;
03. **public** MyCommand(Receiver receiver) {
04. **this**.receiver = receiver;
05. }
06. @Override
07. **public** **void** exe() {
08. receiver.action();
09. }
10. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Receiver {
2. **public** **void** action(){
3. System.out.println("command received!");
4. }
5. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Invoker {
2. **private** Command command;
3. **public** Invoker(Command command) {
4. **this**.command = command;
5. }
6. **public** **void** action(){
7. command.exe();
8. }
9. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. **public** **class** Test {
2. **public** **static** **void** main(String\[] args) {
3. Receiver receiver = **new** Receiver();
4. Command cmd = **new** MyCommand(receiver);
5. Invoker invoker = **new** Invoker(cmd);
6. invoker.action();
7. }
8. }

输出：command received!

这个很哈理解，命令模式的目的就是达到命令的发出者和执行者之间解耦，实现请求和执行分开，熟悉Struts的同学应该知道，Struts其实就是一种将请求和呈现分离的技术，其中必然涉及命令模式的思想！

其实每个设计模式都是很重要的一种思想，看上去很熟，其实是因为我们在学到的东西中都有涉及，尽管有时我们并不知道，其实在Java本身的设计之中处处都有体现，像AWT、JDBC、集合类、IO管道或者是Web框架，里面设计模式无处不在。因为我们篇幅有限，很难讲每一个设计模式都讲的很详细，不过我会尽我所能，尽量在有限的空间和篇幅内，把意思写清楚了，更好让大家明白。本章不出意外的话，应该是设计模式最后一讲了，首先还是上一下上篇开头的那个图：

![](http://dl.iteye.com/upload/attachment/0083/1221/5d3c9b85-c281-3c48-999c-d27095c6ec9f.jpg "点击查看原始大小图片")

本章讲讲第三类和第四类。

## []()类的状态

### []()**19、备忘录模式（Memento）**

主要目的是保存一个对象的某个状态，以便在适当的时候恢复对象，个人觉得叫备份模式更形象些，通俗的讲下：假设有原始类A，A中有各种属性，A可以决定需要备份的属性，备忘录类B是用来存储A的一些内部状态，类C呢，就是一个用来存储备忘录的，且只能存储，不能修改等操作。做个图来分析一下：

![](http://dl.iteye.com/upload/attachment/0083/1223/853d5c5a-9b7b-3341-a72e-abd3cbc3c81f.jpg)

Original类是原始类，里面有需要保存的属性value及创建一个备忘录类，用来保存value值。Memento类是备忘录类，Storage类是存储备忘录的类，持有Memento类的实例，该模式很好理解。直接看源码：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** Original {
02. **private** String value;
03. **public** String getValue() {
04. **return** value;
05. }
06. **public** **void** setValue(String value) {
07. **this**.value = value;
08. }
09. **public** Original(String value) {
10. **this**.value = value;
11. }
12. **public** Memento createMemento(){
13. **return** **new** Memento(value);
14. }
15. **public** **void** restoreMemento(Memento memento){
16. **this**.value = memento.getValue();
17. }
18. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** Memento {
02. **private** String value;
03. **public** Memento(String value) {
04. **this**.value = value;
05. }
06. **public** String getValue() {
07. **return** value;
08. }
09. **public** **void** setValue(String value) {
10. **this**.value = value;
11. }
12. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** Storage {
02. **private** Memento memento;
03. **public** Storage(Memento memento) {
04. **this**.memento = memento;
05. }
06. **public** Memento getMemento() {
07. **return** memento;
08. }
09. **public** **void** setMemento(Memento memento) {
10. **this**.memento = memento;
11. }
12. }

测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** Test {
02. **public** **static** **void** main(String\[] args) {
03. // 创建原始类
04. Original origi = **new** Original("egg");
05. // 创建备忘录
06. Storage storage = **new** Storage(origi.createMemento());
07. // 修改原始类的状态
08. System.out.println("初始化状态为：" + origi.getValue());
09. origi.setValue("niu");
10. System.out.println("修改后的状态为：" + origi.getValue());
11. // 回复原始类的状态
12. origi.restoreMemento(storage.getMemento());
13. System.out.println("恢复后的状态为：" + origi.getValue());
14. }
15. }

输出：

初始化状态为：egg  
修改后的状态为：niu  
恢复后的状态为：egg

简单描述下：新建原始类时，value被初始化为egg，后经过修改，将value的值置为niu，最后倒数第二行进行恢复状态，结果成功恢复了。其实我觉得这个模式叫“备份-恢复”模式最形象。

 

### []()**20、状态模式（State）**

核心思想就是：当对象的状态改变时，同时改变其行为，很好理解！就拿QQ来说，有几种状态，在线、隐身、忙碌等，每个状态对应不同的操作，而且你的好友也能看到你的状态，所以，状态模式就两点：1、可以通过改变状态来获得不同的行为。2、你的好友能同时看到你的变化。看图：

![](http://dl.iteye.com/upload/attachment/0083/1225/006156d2-f41f-3019-a194-b872a59ca426.jpg)

State类是个状态类，Context类可以实现切换，我们来看看代码：

 

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **package** com.xtfggef.dp.state;
02. /\**
03. * 状态类的核心类
04. * 2012-12-1
05. * @author erqing
06. \*
07. \*/
08. **public** **class** State {
09. **private** String value;
10. **public** String getValue() {
11. **return** value;
12. }
13. **public** **void** setValue(String value) {
14. **this**.value = value;
15. }
16. **public** **void** method1(){
17. System.out.println("execute the first opt!");
18. }
19. **public** **void** method2(){
20. System.out.println("execute the second opt!");
21. }
22. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **package** com.xtfggef.dp.state;
02. /\**
03. * 状态模式的切换类   2012-12-1
04. * @author erqing
05. \*
06. \*/
07. **public** **class** Context {
08. **private** State state;
09. **public** Context(State state) {
10. **this**.state = state;
11. }
12. **public** State getState() {
13. **return** state;
14. }
15. **public** **void** setState(State state) {
16. **this**.state = state;
17. }
18. **public** **void** method() {
19. **if** (state.getValue().equals("state1")) {
20. state.method1();
21. } **else** **if** (state.getValue().equals("state2")) {
22. state.method2();
23. }
24. }
25. }

测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** Test {
02. **public** **static** **void** main(String\[] args) {
03. State state = **new** State();
04. Context context = **new** Context(state);
05. //设置第一种状态
06. state.setValue("state1");
07. context.method();
08. //设置第二种状态
09. state.setValue("state2");
10. context.method();
11. }
12. }

输出：

 

execute the first opt!  
execute the second opt!

根据这个特性，状态模式在日常开发中用的挺多的，尤其是做网站的时候，我们有时希望根据对象的某一属性，区别开他们的一些功能，比如说简单的权限控制等。

 

 

## []()通过中间类

### []()**21、访问者模式（Visitor）**

 

访问者模式把数据结构和作用于结构上的操作解耦合，使得操作集合可相对自由地演化。访问者模式适用于数据结构相对稳定算法又易变化的系统。因为访问者模式使得算法操作增加变得容易。若系统数据结构对象易于变化，经常有新的数据对象增加进来，则不适合使用访问者模式。访问者模式的优点是增加操作很容易，因为增加操作意味着增加新的访问者。访问者模式将有关行为集中到一个访问者对象中，其改变不影响系统数据结构。其缺点就是增加新的数据结构很困难。—— From 百科

简单来说，访问者模式就是一种分离对象数据结构与行为的方法，通过这种分离，可达到为一个被访问者动态添加新的操作而无需做其它的修改的效果。简单关系图：

![](http://dl.iteye.com/upload/attachment/0083/1227/96bd38f3-2888-3cc5-b90f-0e7542dc5845.jpg)

来看看原码：一个Visitor类，存放要访问的对象，

 

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **interface** Visitor {
2. **public** **void** visit(Subject sub);
3. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** MyVisitor **implements** Visitor {
2. @Override
3. **public** **void** visit(Subject sub) {
4. System.out.println("visit the subject："+sub.getSubject());
5. }
6. }

Subject类，accept方法，接受将要访问它的对象，getSubject()获取将要被访问的属性，

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **interface** Subject {
2. **public** **void** accept(Visitor visitor);
3. **public** String getSubject();
4. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** MySubject **implements** Subject {
02. @Override
03. **public** **void** accept(Visitor visitor) {
04. visitor.visit(**this**);
05. }
06. @Override
07. **public** String getSubject() {
08. **return** "love";
09. }
10. }

测试：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** Test {
2. **public** **static** **void** main(String\[] args) {
3. Visitor visitor = **new** MyVisitor();
4. Subject sub = **new** MySubject();
5. sub.accept(visitor);
6. }
7. }

输出：visit the subject：love

 

该模式适用场景：如果我们想为一个现有的类增加新功能，不得不考虑几个事情：1、新功能会不会与现有功能出现兼容性问题？2、以后会不会再需要添加？3、如果类不允许修改代码怎么办？面对这些问题，最好的解决方法就是使用访问者模式，访问者模式适用于数据结构相对稳定的系统，把数据结构和算法解耦，

 

### []()**22、中介者模式（Mediator）**

 

中介者模式也是用来降低类类之间的耦合的，因为如果类类之间有依赖关系的话，不利于功能的拓展和维护，因为只要修改一个对象，其它关联的对象都得进行修改。如果使用中介者模式，只需关心和Mediator类的关系，具体类类之间的关系及调度交给Mediator就行，这有点像spring容器的作用。先看看图：

![](http://dl.iteye.com/upload/attachment/0083/1229/f1f2cc36-ab27-32fa-9906-9cdee2c2b625.jpg)

User类统一接口，User1和User2分别是不同的对象，二者之间有关联，如果不采用中介者模式，则需要二者相互持有引用，这样二者的耦合度很高，为了解耦，引入了Mediator类，提供统一接口，MyMediator为其实现类，里面持有User1和User2的实例，用来实现对User1和User2的控制。这样User1和User2两个对象相互独立，他们只需要保持好和Mediator之间的关系就行，剩下的全由MyMediator类来维护！基本实现：

 

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **interface** Mediator {
2. **public** **void** createMediator();
3. **public** **void** workAll();
4. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** MyMediator **implements** Mediator {
02. **private** User user1;
03. **private** User user2;
04. **public** User getUser1() {
05. **return** user1;
06. }
07. **public** User getUser2() {
08. **return** user2;
09. }
10. @Override
11. **public** **void** createMediator() {
12. user1 = **new** User1(**this**);
13. user2 = **new** User2(**this**);
14. }
15. @Override
16. **public** **void** workAll() {
17. user1.work();
18. user2.work();
19. }
20. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **abstract** **class** User {
02. **private** Mediator mediator;
03. **public** Mediator getMediator(){
04. **return** mediator;
05. }
06. **public** User(Mediator mediator) {
07. **this**.mediator = mediator;
08. }
09. **public** **abstract** **void** work();
10. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** User1 **extends** User {
2. **public** User1(Mediator mediator){
3. **super**(mediator);
4. }
5. @Override
6. **public** **void** work() {
7. System.out.println("user1 exe!");
8. }
9. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** User2 **extends** User {
2. **public** User2(Mediator mediator){
3. **super**(mediator);
4. }
5. @Override
6. **public** **void** work() {
7. System.out.println("user2 exe!");
8. }
9. }

测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** Test {
2. **public** **static** **void** main(String\[] args) {
3. Mediator mediator = **new** MyMediator();
4. mediator.createMediator();
5. mediator.workAll();
6. }
7. }

输出：

user1 exe!  
user2 exe!

 

### []()**23、解释器模式（Interpreter）**

解释器模式是我们暂时的最后一讲，一般主要应用在OOP开发中的编译器的开发中，所以适用面比较窄。

 

![](http://dl.iteye.com/upload/attachment/0083/1231/c87e402e-a355-3761-9ce3-7978956ba475.jpg)

Context类是一个上下文环境类，Plus和Minus分别是用来计算的实现，代码如下：

 

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **interface** Expression {
2. **public** **int** interpret(Context context);
3. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** Plus **implements** Expression {
2. @Override
3. **public** **int** interpret(Context context) {
4. **return** context.getNum1()+context.getNum2();
5. }
6. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** Minus **implements** Expression {
2. @Override
3. **public** **int** interpret(Context context) {
4. **return** context.getNum1()-context.getNum2();
5. }
6. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

01. **public** **class** Context {
02. **private** **int** num1;
03. **private** **int** num2;
04. **public** Context(**int** num1, **int** num2) {
05. **this**.num1 = num1;
06. **this**.num2 = num2;
07. }
08. **public** **int** getNum1() {
09. **return** num1;
10. }
11. **public** **void** setNum1(**int** num1) {
12. **this**.num1 = num1;
13. }
14. **public** **int** getNum2() {
15. **return** num2;
16. }
17. **public** **void** setNum2(**int** num2) {
18. **this**.num2 = num2;
19. }
20. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8245537 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8245537 "copy")

1. **public** **class** Test {
2. **public** **static** **void** main(String\[] args) {
3. // 计算9+2-8的值
4. **int** result = **new** Minus().interpret((**new** Context(**new** Plus()
5. .interpret(**new** Context(9, 2)), 8)));
6. System.out.println(result);
7. }
8. }

最后输出正确的结果：3。

基本就这样，解释器模式用来做各种各样的解释器，如正则表达式等的解释器等等！