常用设计模式及例子(五)



13、策略模式(strategy)

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

首先统一接口:

[java]  view plain copy
  1. public interface ICalculator {  
  2.     public int calculate(String exp);  
  3. }  

辅助类:

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

三个实现类:

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

简单的测试类:

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

输出:10

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

14、模板方法模式(Template Method)

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

[java]  view plain copy
  1. public abstract class AbstractCalculator {  
  2.       
  3.     /*主方法,实现对本类其它方法的调用*/  
  4.     public final int calculate(String exp,String opt){  
  5.         int array[] = split(exp,opt);  
  6.         return calculate(array[0],array[1]);  
  7.     }  
  8.       
  9.     /*被子类重写的方法*/  
  10.     abstract public int calculate(int num1,int num2);  
  11.       
  12.     public int[] split(String exp,String opt){  
  13.         String array[] = exp.split(opt);  
  14.         int arrayInt[] = new int[2];  
  15.         arrayInt[0] = Integer.parseInt(array[0]);  
  16.         arrayInt[1] = Integer.parseInt(array[1]);  
  17.         return arrayInt;  
  18.     }  
  19. }  
[java]  view plain copy
  1. public class Plus extends AbstractCalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(int num1,int num2) {  
  5.         return num1 + num2;  
  6.     }  
  7. }  

测试类:

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

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

15、观察者模式(Observer)

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

一个Observer接口:

[java]  view plain copy
  1. public interface Observer {  
  2.     public void update();  
  3. }  

两个实现类:

[java]  view plain copy
  1. public class Observer1 implements Observer {  
  2.   
  3.     @Override  
  4.     public void update() {  
  5.         System.out.println("observer1 has received!");  
  6.     }  
  7. }  
[java]  view plain copy
  1. public class Observer2 implements Observer {  
  2.   
  3.     @Override  
  4.     public void update() {  
  5.         System.out.println("observer2 has received!");  
  6.     }  
  7.   
  8. }  

Subject接口及实现类:

[java]  view plain copy
  1. public interface Subject {  
  2.       
  3.     /*增加观察者*/  
  4.     public void add(Observer observer);  
  5.       
  6.     /*删除观察者*/  
  7.     public void del(Observer observer);  
  8.       
  9.     /*通知所有的观察者*/  
  10.     public void notifyObservers();  
  11.       
  12.     /*自身的操作*/  
  13.     public void operation();  
  14. }  
[java]  view plain copy
  1. public abstract class AbstractSubject implements Subject {  
  2.   
  3.     private Vector<Observer> vector = new Vector<Observer>();  
  4.     @Override  
  5.     public void add(Observer observer) {  
  6.         vector.add(observer);  
  7.     }  
  8.   
  9.     @Override  
  10.     public void del(Observer observer) {  
  11.         vector.remove(observer);  
  12.     }  
  13.   
  14.     @Override  
  15.     public void notifyObservers() {  
  16.         Enumeration<Observer> enumo = vector.elements();  
  17.         while(enumo.hasMoreElements()){  
  18.             enumo.nextElement().update();  
  19.         }  
  20.     }  
  21. }  
[java]  view plain copy
  1. public class MySubject extends AbstractSubject {  
  2.   
  3.     @Override  
  4.     public void operation() {  
  5.         System.out.println("update self!");  
  6.         notifyObservers();  
  7.     }  
  8.   
  9. }  


测试类:

[java]  view plain copy
  1. public class ObserverTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Subject sub = new MySubject();  
  5.         sub.add(new Observer1());  
  6.         sub.add(new Observer2());  
  7.           
  8.         sub.operation();  
  9.     }  
  10.   
  11. }  

输出:

update self!
observer1 has received!
observer2 has received!

16、迭代子模式(Iterator)

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

两个接口:

[java]  view plain copy
  1. public interface Collection {  
  2.       
  3.     public Iterator iterator();  
  4.       
  5.     /*取得集合元素*/  
  6.     public Object get(int i);  
  7.       
  8.     /*取得集合大小*/  
  9.     public int size();  
  10. }  
[java]  view plain copy
  1. public interface Iterator {  
  2.     //前移  
  3.     public Object previous();  
  4.       
  5.     //后移  
  6.     public Object next();  
  7.     public boolean hasNext();  
  8.       
  9.     //取得第一个元素  
  10.     public Object first();  
  11. }  

两个实现:

[java]  view plain copy
  1. public class MyCollection implements Collection {  
  2.   
  3.     public String string[] = {"A","B","C","D","E"};  
  4.     @Override  
  5.     public Iterator iterator() {  
  6.         return new MyIterator(this);  
  7.     }  
  8.   
  9.     @Override  
  10.     public Object get(int i) {  
  11.         return string[i];  
  12.     }  
  13.   
  14.     @Override  
  15.     public int size() {  
  16.         return string.length;  
  17.     }  
  18. }  
[java]  view plain copy
  1. public class MyIterator implements Iterator {  
  2.   
  3.     private Collection collection;  
  4.     private int pos = -1;  
  5.       
  6.     public MyIterator(Collection collection){  
  7.         this.collection = collection;  
  8.     }  
  9.       
  10.     @Override  
  11.     public Object previous() {  
  12.         if(pos > 0){  
  13.             pos--;  
  14.         }  
  15.         return collection.get(pos);  
  16.     }  
  17.   
  18.     @Override  
  19.     public Object next() {  
  20.         if(pos<collection.size()-1){  
  21.             pos++;  
  22.         }  
  23.         return collection.get(pos);  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean hasNext() {  
  28.         if(pos<collection.size()-1){  
  29.             return true;  
  30.         }else{  
  31.             return false;  
  32.         }  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object first() {  
  37.         pos = 0;  
  38.         return collection.get(pos);  
  39.     }  
  40.   
  41. }  

测试类:

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

输出:A B C D E

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

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

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

[java]  view plain copy
  1. public interface Handler {  
  2.     public void operator();  
  3. }  
[java]  view plain copy
  1. public abstract class AbstractHandler {  
  2.       
  3.     private Handler handler;  
  4.   
  5.     public Handler getHandler() {  
  6.         return handler;  
  7.     }  
  8.   
  9.     public void setHandler(Handler handler) {  
  10.         this.handler = handler;  
  11.     }  
  12.       
  13. }  
[java]  view plain copy
  1. public class MyHandler extends AbstractHandler implements Handler {  
  2.   
  3.     private String name;  
  4.   
  5.     public MyHandler(String name) {  
  6.         this.name = name;  
  7.     }  
  8.   
  9.     @Override  
  10.     public void operator() {  
  11.         System.out.println(name+"deal!");  
  12.         if(getHandler()!=null){  
  13.             getHandler().operator();  
  14.         }  
  15.     }  
  16. }  
[java]  view plain copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         MyHandler h1 = new MyHandler("h1");  
  5.         MyHandler h2 = new MyHandler("h2");  
  6.         MyHandler h3 = new MyHandler("h3");  
  7.   
  8.         h1.setHandler(h2);  
  9.         h2.setHandler(h3);  
  10.   
  11.         h1.operator();  
  12.     }  
  13. }  

输出:

h1deal!
h2deal!
h3deal!

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

18、命令模式(Command)

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

Invoker是调用者(司令员),Receiver是被调用者(士兵),MyCommand是命令,实现了Command接口,持有接收对象,看实现代码:

[java]  view plain copy
  1. public interface Command {  
  2.     public void exe();  
  3. }  
[java]  view plain copy
  1. public class MyCommand implements Command {  
  2.   
  3.     private Receiver receiver;  
  4.       
  5.     public MyCommand(Receiver receiver) {  
  6.         this.receiver = receiver;  
  7.     }  
  8.   
  9.     @Override  
  10.     public void exe() {  
  11.         receiver.action();  
  12.     }  
  13. }  
[java]  view plain copy
  1. public class Receiver {  
  2.     public void action(){  
  3.         System.out.println("command received!");  
  4.     }  
  5. }  
[java]  view plain copy
  1. public class Invoker {  
  2.       
  3.     private Command command;  
  4.       
  5.     public Invoker(Command command) {  
  6.         this.command = command;  
  7.     }  
  8.   
  9.     public void action(){  
  10.         command.exe();  
  11.     }  
  12. }  
[java]  view plain copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Receiver receiver = new Receiver();  
  5.         Command cmd = new MyCommand(receiver);  
  6.         Invoker invoker = new Invoker(cmd);  
  7.         invoker.action();  
  8.     }  
  9. }  

输出:command received!

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

19、备忘录模式(Memento)

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

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

[java]  view plain copy
  1. public class Original {  
  2.       
  3.     private String value;  
  4.       
  5.     public String getValue() {  
  6.         return value;  
  7.     }  
  8.   
  9.     public void setValue(String value) {  
  10.         this.value = value;  
  11.     }  
  12.   
  13.     public Original(String value) {  
  14.         this.value = value;  
  15.     }  
  16.   
  17.     public Memento createMemento(){  
  18.         return new Memento(value);  
  19.     }  
  20.       
  21.     public void restoreMemento(Memento memento){  
  22.         this.value = memento.getValue();  
  23.     }  
  24. }  
[java]  view plain copy
  1. public class Memento {  
  2.       
  3.     private String value;  
  4.   
  5.     public Memento(String value) {  
  6.         this.value = value;  
  7.     }  
  8.   
  9.     public String getValue() {  
  10.         return value;  
  11.     }  
  12.   
  13.     public void setValue(String value) {  
  14.         this.value = value;  
  15.     }  
  16. }  
[java]  view plain copy
  1. public class Storage {  
  2.       
  3.     private Memento memento;  
  4.       
  5.     public Storage(Memento memento) {  
  6.         this.memento = memento;  
  7.     }  
  8.   
  9.     public Memento getMemento() {  
  10.         return memento;  
  11.     }  
  12.   
  13.     public void setMemento(Memento memento) {  
  14.         this.memento = memento;  
  15.     }  
  16. }  

测试类:

[java]  view plain copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         // 创建原始类  
  6.         Original origi = new Original("egg");  
  7.   
  8.         // 创建备忘录  
  9.         Storage storage = new Storage(origi.createMemento());  
  10.   
  11.         // 修改原始类的状态  
  12.         System.out.println("初始化状态为:" + origi.getValue());  
  13.         origi.setValue("niu");  
  14.         System.out.println("修改后的状态为:" + origi.getValue());  
  15.   
  16.         // 回复原始类的状态  
  17.         origi.restoreMemento(storage.getMemento());  
  18.         System.out.println("恢复后的状态为:" + origi.getValue());  
  19.     }  
  20. }  

输出:

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

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

20、状态模式(State)

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

[java]  view plain copy
  1. package com.xtfggef.dp.state;  
  2.   
  3. /** 
  4.  * 状态类的核心类 
  5.  * 2012-12-1 
  6.  * @author erqing 
  7.  * 
  8.  */  
  9. public class State {  
  10.       
  11.     private String value;  
  12.       
  13.     public String getValue() {  
  14.         return value;  
  15.     }  
  16.   
  17.     public void setValue(String value) {  
  18.         this.value = value;  
  19.     }  
  20.   
  21.     public void method1(){  
  22.         System.out.println("execute the first opt!");  
  23.     }  
  24.       
  25.     public void method2(){  
  26.         System.out.println("execute the second opt!");  
  27.     }  
  28. }  
[java]  view plain copy
  1. package com.xtfggef.dp.state;  
  2.   
  3. /** 
  4.  * 状态模式的切换类   2012-12-1 
  5.  * @author erqing 
  6.  *  
  7.  */  
  8. public class Context {  
  9.   
  10.     private State state;  
  11.   
  12.     public Context(State state) {  
  13.         this.state = state;  
  14.     }  
  15.   
  16.     public State getState() {  
  17.         return state;  
  18.     }  
  19.   
  20.     public void setState(State state) {  
  21.         this.state = state;  
  22.     }  
  23.   
  24.     public void method() {  
  25.         if (state.getValue().equals("state1")) {  
  26.             state.method1();  
  27.         } else if (state.getValue().equals("state2")) {  
  28.             state.method2();  
  29.         }  
  30.     }  
  31. }  

测试类:

 

 

[java]  view plain copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         State state = new State();  
  6.         Context context = new Context(state);  
  7.           
  8.         //设置第一种状态  
  9.         state.setValue("state1");  
  10.         context.method();  
  11.           
  12.         //设置第二种状态  
  13.         state.setValue("state2");  
  14.         context.method();  
  15.     }  
  16. }  

输出:

 

execute the first opt!
execute the second opt!

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

21、访问者模式(Visitor)

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

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

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

 

[java]  view plain copy
  1. public interface Visitor {  
  2.     public void visit(Subject sub);  
  3. }  
[java]  view plain copy
  1. public class MyVisitor implements Visitor {  
  2.   
  3.     @Override  
  4.     public void visit(Subject sub) {  
  5.         System.out.println("visit the subject:"+sub.getSubject());  
  6.     }  
  7. }  

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

[java]  view plain copy
  1. public interface Subject {  
  2.     public void accept(Visitor visitor);  
  3.     public String getSubject();  
  4. }  
[java]  view plain copy
  1. public class MySubject implements Subject {  
  2.   
  3.     @Override  
  4.     public void accept(Visitor visitor) {  
  5.         visitor.visit(this);  
  6.     }  
  7.   
  8.     @Override  
  9.     public String getSubject() {  
  10.         return "love";  
  11.     }  
  12. }  

测试:

 

 

 

 

 

 

 

 

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

输出:visit the subject:love

 

 

 

 

 

 

 

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

22、中介者模式(Mediator)

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

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

 

[java]  view plain copy
  1. public interface Mediator {  
  2.     public void createMediator();  
  3.     public void workAll();  
  4. }  
[java]  view plain copy
  1. public class MyMediator implements Mediator {  
  2.   
  3.     private User user1;  
  4.     private User user2;  
  5.       
  6.     public User getUser1() {  
  7.         return user1;  
  8.     }  
  9.   
  10.     public User getUser2() {  
  11.         return user2;  
  12.     }  
  13.   
  14.     @Override  
  15.     public void createMediator() {  
  16.         user1 = new User1(this);  
  17.         user2 = new User2(this);  
  18.     }  
  19.   
  20.     @Override  
  21.     public void workAll() {  
  22.         user1.work();  
  23.         user2.work();  
  24.     }  
  25. }  
[java]  view plain copy
  1. public abstract class User {  
  2.       
  3.     private Mediator mediator;  
  4.       
  5.     public Mediator getMediator(){  
  6.         return mediator;  
  7.     }  
  8.       
  9.     public User(Mediator mediator) {  
  10.         this.mediator = mediator;  
  11.     }  
  12.   
  13.     public abstract void work();  
  14. }  
[java]  view plain copy
  1. public class User1 extends User {  
  2.   
  3.     public User1(Mediator mediator){  
  4.         super(mediator);  
  5.     }  
  6.       
  7.     @Override  
  8.     public void work() {  
  9.         System.out.println("user1 exe!");  
  10.     }  
  11. }  
[java]  view plain copy
  1. public class User2 extends User {  
  2.   
  3.     public User2(Mediator mediator){  
  4.         super(mediator);  
  5.     }  
  6.       
  7.     @Override  
  8.     public void work() {  
  9.         System.out.println("user2 exe!");  
  10.     }  
  11. }  

测试类:

 

 

 

 

 

 

 

 

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

输出:

 

 

 

 

 

 

 

user1 exe!
user2 exe!

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

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

 

[java]  view plain copy
  1. public interface Expression {  
  2.     public int interpret(Context context);  
  3. }  
[java]  view plain copy
  1. public class Plus implements Expression {  
  2.   
  3.     @Override  
  4.     public int interpret(Context context) {  
  5.         return context.getNum1()+context.getNum2();  
  6.     }  
  7. }  
[java]  view plain copy
  1. public class Minus implements Expression {  
  2.   
  3.     @Override  
  4.     public int interpret(Context context) {  
  5.         return context.getNum1()-context.getNum2();  
  6.     }  
  7. }  
[java]  view plain copy
  1. public class Context {  
  2.       
  3.     private int num1;  
  4.     private int num2;  
  5.       
  6.     public Context(int num1, int num2) {  
  7.         this.num1 = num1;  
  8.         this.num2 = num2;  
  9.     }  
  10.       
  11.     public int getNum1() {  
  12.         return num1;  
  13.     }  
  14.     public void setNum1(int num1) {  
  15.         this.num1 = num1;  
  16.     }  
  17.     public int getNum2() {  
  18.         return num2;  
  19.     }  
  20.     public void setNum2(int num2) {  
  21.         this.num2 = num2;  
  22.     }  
  23.       
  24.       
  25. }  
[java]  view plain copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         // 计算9+2-8的值  
  6.         int result = new Minus().interpret((new Context(new Plus()  
  7.                 .interpret(new Context(9, 2)), 8)));  
  8.         System.out.println(result);  
  9.     }  
  10. }  

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

 

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

资源:http://download.csdn.net/detail/zhangerqing/4835830

 

原文链接:http://blog.csdn.net/zhangerqing

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值