Java开发中的23种设计模式详解 【转】

创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。

行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

 

1、开闭原则(Open Close Principle)

2、里氏代换原则(Liskov Substitution Principle)

3、依赖倒转原则(Dependence Inversion Principle)

4、接口隔离原则(Interface Segregation Principle)

架构出发,为了升级和维护方便。所以上文中多次出现:降低依赖,降低耦合。

为什么叫最少知道原则,就是说:一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。

原则是尽量使用合成/聚合的方式,而不是使用继承。

Java的23中设计模式

1、工厂方法模式(Factory Method)

11、普通工厂模式,就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。首先看下关系图:

举例如下:(我们举一个发送邮件和短信的例子)

首先,创建二者的共同接口:

public interface Sender {  

  •     public void Send();  
  • }  

其次,创建实现类:

public class MailSender implements Sender {  

  •     @Override  
  •     public void Send() {  
  •         System.out.println("this is mailsender!");  
  •     }  
  • }  

public class SmsSender implements Sender {  

  •   
  •     @Override  
  •     public void Send() {  
  •         System.out.println("this is sms sender!");  
  •     }  
  • }  

最后,建工厂类:

public class SendFactory {  

  •   
  •     public Sender produce(String type) {  
  •         if ("mail".equals(type)) {  
  •             return new MailSender();  
  •         } else if ("sms".equals(type)) {  
  •             return new SmsSender();  
  •         } else {  
  •             System.out.println("请输入正确的类型!");  
  •             return null;  
  •         }  
  •     }  
  • }  

我们来测试下:

  • public class FactoryTest {  
  •   
  •     public static void main(String[] args) {  
  •         SendFactory factory = new SendFactory();  
  •         Sender sender = factory.produce("sms");  
  •         sender.Send();  
  •     }  
  • }  

22、多个工厂方法模式,是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象。关系图:

将上面的代码做下修改,改动下SendFactory类就行,如下:

[java] view plaincopy  SendFactory {  
    Sender produceMail(){  

        return new MailSender();  

  •     }  
  •       
  •     public Sender produceSms(){  
  •         return new SmsSender();  
  •     }  
  • }  

测试类如下:

public class FactoryTest {  

  •   
  •     public static void main(String[] args) {  
  •         SendFactory factory = new SendFactory();  
  •         Sender sender = factory.produceMail();  
  •         sender.Send();  
  •     }  
  • }  

33、静态工厂方法模式,将上面的多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可。

public class SendFactory {  

  •       
  •     public static Sender produceMail(){  
  •         return new MailSender();  
  •     }  
  •       
  •     public static Sender produceSms(){  
  •         return new SmsSender();  
  •     }  
  • }  

public class FactoryTest {  

  •   
  •     public static void main(String[] args) {      
  •         Sender sender = SendFactory.produceMail();  
  •         sender.Send();  
  •     }  
  • }  

总体来说,工厂模式适合:凡是出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建。在以上的三种模式中,第一种如果传入的字符串有误,不能正确创建对象,第三种相对于第二种,不需要实例化工厂类,所以,大多数情况下,我们会选用第三种——静态工厂方法模式。

工厂方法模式有一个问题就是,类的创建依赖工厂类,也就是说,如果想要拓展程序,必须对工厂类进行修改,这违背了闭包原则,所以,从设计角度考虑,有一定的问题,如何解决?就用到抽象工厂模式,创建多个工厂类,这样一旦需要增加新的功能,直接增加新的工厂类就可以了,不需要修改之前的代码。因为抽象工厂不太好理解,我们先看看图,然后就和代码,就比较容易理解。

请看例子:

public interface Sender {  

  •     public void Send();  
  • }  

两个实现类:

public class MailSender implements Sender {  

  •     @Override  
  •     public void Send() {  
  •         System.out.println("this is mailsender!");  
  •     }  
  • }  

public class SmsSender implements Sender {  

  •   
  •     @Override  
  •     public void Send() {  
  •         System.out.println("this is sms sender!");  
  •     }  
  • }  

两个工厂类:

public class SendMailFactory implements Provider {  

  •       
  •     @Override  
  •     public Sender produce(){  
  •         return new MailSender();  
  •     }  
  • }  

public class SendSmsFactory implements Provider{  

  •   
  •     @Override  
  •     public Sender produce() {  
  •         return new SmsSender();  
  •     }  
  • }  

在提供一个接口:

public interface Provider {  

  •     public Sender produce();  
  • }  

测试类:

public class Test {  

  •   
  •     public static void main(String[] args) {  
  •         Provider provider = new SendMailFactory();  
  •         Sender sender = provider.produce();  
  •         sender.Send();  
  •     }  
  • }  

3、单例模式(Singleton

1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。

3、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。(比如一个军队出现了多个司令员同时指挥,肯定会乱成一团),所以只有使用单例模式,才能保证核心交易服务器独立控制整个流程。

首先我们写一个简单的单例类:

public class Singleton {  

  •   
  •     /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */  
  •     private static Singleton instance = null;  
  •   
  •     /* 私有构造方法,防止被实例化 */  
  •     private Singleton() {  
  •     }  
  •   
  •     /* 静态工程方法,创建实例 */  
  •     public static Singleton getInstance() {  
  •         if (instance == null) {  
  •             instance = new Singleton();  
  •         }  
  •         return instance;  
  •     }  
  •   
  •     /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */  
  •     public Object readResolve() {  
  •         return instance;  
  •     }  
  • }  


这个类可以满足基本要求,但是,像这样毫无线程安全保护的类,如果我们把它放入多线程的环境下,肯定就会出现问题了,如何解决?我们首先会想到对getInstance方法加synchronized关键字,如下:

[java] view plaincopy

public static synchronized Singleton getInstance() {  

  •         if (instance == null) {  
  •             instance = new Singleton();  
  •         }  
  •         return instance;  
  •     }  

但是,synchronized关键字锁住的是这个对象,这样的用法,在性能上会有所下降,因为每次调用getInstance(),都要对对象上锁,事实上,只有在第一次创建对象的时候需要加锁,之后就不需要了,所以,这个地方需要改进。我们改成下面这个:

[java] view plaincopy

public static Singleton getInstance() {  

  •         if (instance == null) {  
  •             synchronized (instance) {  
  •                 if (instance == null) {  
  •                     instance = new Singleton();  
  •                 }  
  •             }  
  •         }  
  •         return instance;  
  •     }  

似乎解决了之前提到的问题,将synchronized关键字加在了内部,也就是说当调用的时候是不需要加锁的,只有在instance为null,并创建对象的时候才需要加锁,性能有一定的提升。但是,这样的情况,还是有可能有问题的,看下面的情况:在Java指令中创建对象和赋值操作是分开进行的,也就是说instance = new Singleton();语句是分两步执行的。但是JVM并不保证这两个操作的先后顺序,也就是说有可能JVM会为新的Singleton实例分配空间,然后直接赋值给instance成员,然后再去初始化这个Singleton实例。这样就可能出错了,我们以A、B两个线程为例:

a>A、B线程同时进入了第一个if判断

b>A首先进入synchronized块,由于instance为null,所以它执行instance = new Singleton();

c>由于JVM内部的优化机制,JVM先画出了一些分配给Singleton实例的空白内存,并赋值给instance成员(注意此时JVM没有开始初始化这个实例),然后A离开了synchronized块。

d>B进入synchronized块,由于instance此时不是null,因此它马上离开了synchronized块并将结果返回给调用该方法的程序。

e>此时B线程打算使用Singleton实例,却发现它没有被初始化,于是错误发生了。

所以程序还是有可能发生错误,其实程序在运行过程是很复杂的,从这点我们就可以看出,尤其是在写多线程环境下的程序更有难度,有挑战性。我们对该程序做进一步优化:

[java] view plaincopy

private static class SingletonFactory{           

  •         private static Singleton instance = new Singleton();           
  •     }           
  •     public static Singleton getInstance(){           
  •         return SingletonFactory.instance;           
  •     }   

实际情况是,单例模式使用内部类来维护单例的实现,JVM内部的机制能够保证当一个类被加载的时候,这个类的加载过程是线程互斥的。这样当我们第一次调用getInstance的时候,JVM能够帮我们保证instance只被创建一次,并且会保证把赋值给instance的内存初始化完毕,这样我们就不用担心上面的问题。同时该方法也只会在第一次调用的时候使用互斥机制,这样就解决了低性能问题。这样我们暂时总结一个完美的单例模式:

[java] view plaincopy

public class Singleton {  

  •   
  •     /* 私有构造方法,防止被实例化 */  
  •     private Singleton() {  
  •     }  
  •   
  •     /* 此处使用一个内部类来维护单例 */  
  •     private static class SingletonFactory {  
  •         private static Singleton instance = new Singleton();  
  •     }  
  •   
  •     /* 获取实例 */  
  •     public static Singleton getInstance() {  
  •         return SingletonFactory.instance;  
  •     }  
  •   
  •     /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */  
  •     public Object readResolve() {  
  •         return getInstance();  
  •     }  
  • }  

其实说它完美,也不一定,如果在构造函数中抛出异常,实例将永远得不到创建,也会出错。所以说,十分完美的东西是没有的,我们只能根据实际情况,选择最适合自己应用场景的实现方法。也有人这样实现:因为我们只需要在创建类的时候进行同步,所以只要将创建和getInstance()分开,单独为创建加synchronized关键字,也是可以的:

[java] view plaincopy

public class SingletonTest {  

  •   
  •     private static SingletonTest instance = null;  
  •   
  •     private SingletonTest() {  
  •     }  
  •   
  •     private static synchronized void syncInit() {  
  •         if (instance == null) {  
  •             instance = new SingletonTest();  
  •         }  
  •     }  
  •   
  •     public static SingletonTest getInstance() {  
  •         if (instance == null) {  
  •             syncInit();  
  •         }  
  •         return instance;  
  •     }  
  • }  

补充:采用"影子实例"的办法为单例对象的属性同步更新

[java] view plaincopy

public class SingletonTest {  

  •   
  •     private static SingletonTest instance = null;  
  •     private Vector properties = null;  
  •   
  •     public Vector getProperties() {  
  •         return properties;  
  •     }  
  •   
  •     private SingletonTest() {  
  •     }  
  •   
  •     private static synchronized void syncInit() {  
  •         if (instance == null) {  
  •             instance = new SingletonTest();  
  •         }  
  •     }  
  •   
  •     public static SingletonTest getInstance() {  
  •         if (instance == null) {  
  •             syncInit();  
  •         }  
  •         return instance;  
  •     }  
  •   
  •     public void updateProperties() {  
  •         SingletonTest shadow = new SingletonTest();  
  •         properties = shadow.getProperties();  
  •     }  
  • }  

1、单例模式理解起来简单,但是具体实现起来还是有一定的难度。

到这儿,单例模式基本已经讲完了,结尾处,笔者突然想到另一个问题,就是采用类的静态方法,实现单例模式的效果,也是可行的,此处二者有什么不同?

其次,单例可以被延迟初始化,静态类一般在第一次加载是初始化。之所以延迟加载,是因为有些类比较庞大,所以延迟加载有助于提升性能。

最后一点,单例类比较灵活,毕竟从实现上只是一个普通的Java类,只要满足单例的基本需求,你可以在里面随心所欲的实现一些其它功能,但是静态类不行。从上面这些概括中,基本可以看出二者的区别,但是,从另一方面讲,我们上面最后实现的那个单例模式,内部就是用一个静态类来实现的,所以,二者有很大的关联,只是我们考虑问题的层面不同罢了。两种思想的结合,才能造就出完美的解决方案,就像HashMap采用数组+链表来实现一样,其实生活中很多事情都是这样,单用不同的方法来处理问题,总是有优点也有缺点,最完美的方法是,结合各个方法的优点,才能最好的解决问题!

工厂类模式提供的是创建单个类的模式,而建造者模式则是将各种产品集中起来进行管理,用来创建复合对象,所谓复合对象就是指某个类具有不同的属性,其实建造者模式就是前面抽象工厂模式和最后的Test结合起来得到的。我们看一下代码:

还和前面一样,一个Sender接口,两个实现类MailSender和SmsSender。最后,建造者类如下:

[java] view plaincopy

public class Builder {  

  •       
  •     private List<Sender> list = new ArrayList<Sender>();  
  •       
  •     public void produceMailSender(int count){  
  •         for(int i=0; i<count; i++){  
  •             list.add(new MailSender());  
  •         }  
  •     }  
  •       
  •     public void produceSmsSender(int count){  
  •         for(int i=0; i<count; i++){  
  •             list.add(new SmsSender());  
  •         }  
  •     }  
  • }  

测试类:

[java] view plaincopy

public class Test {  

  •   
  •     public static void main(String[] args) {  
  •         Builder builder = new Builder();  
  •         builder.produceMailSender(10);  
  •     }  
  • }  

5、原型模式(Prototype)

原型模式虽然是创建型的模式,但是与工程模式没有关系,从名字即可看出,该模式的思想就是将一个对象作为原型,对其进行复制、克隆,产生一个和原对象类似的新对象。本小结会通过对象的复制,进行讲解。在Java中,复制对象是通过clone()实现的,先创建一个原型类:

[java] view plaincopy

public class Prototype implements Cloneable {  

  •   
  •     public Object clone() throws CloneNotSupportedException {  
  •         Prototype proto = (Prototype) super.clone();  
  •         return proto;  
  •     }  
  • }  

浅复制:将一个对象复制后,基本数据类型的变量都会重新创建,而引用类型,指向的还是原对象所指向的。

此处,写一个深浅复制的例子:

[java] view plaincopy

public class Prototype implements Cloneable, Serializable {  

  •   
  •     private static final long serialVersionUID = 1L;  
  •     private String string;  
  •   
  •     private SerializableObject obj;  
  •   
  •     /* 浅复制 */  
  •     public Object clone() throws CloneNotSupportedException {  
  •         Prototype proto = (Prototype) super.clone();  
  •         return proto;  
  •     }  
  •   
  •     /* 深复制 */  
  •     public Object deepClone() throws IOException, ClassNotFoundException {  
  •   
  •         /* 写入当前对象的二进制流 */  
  •         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  •         ObjectOutputStream oos = new ObjectOutputStream(bos);  
  •         oos.writeObject(this);  
  •   
  •         /* 读出二进制流产生的新对象 */  
  •         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());  
  •         ObjectInputStream ois = new ObjectInputStream(bis);  
  •         return ois.readObject();  
  •     }  
  •   
  •     public String getString() {  
  •         return string;  
  •     }  
  •   
  •     public void setString(String string) {  
  •         this.string = string;  
  •     }  
  •   
  •     public SerializableObject getObj() {  
  •         return obj;  
  •     }  
  •   
  •     public void setObj(SerializableObject obj) {  
  •         this.obj = obj;  
  •     }  
  •   
  • }  
  •   
  • class SerializableObject implements Serializable {  
  •     private static final long serialVersionUID = 1L;  
  • }  
 
要实现深复制,需要采用流的形式读入当前对象的二进制输入,再写出二进制数据对应的对象。

类的适配器模式,先看类图:

核心思想就是:有一个Source类,拥有一个方法,待适配,目标接口时Targetable,通过Adapter类,将Source的功能扩展到Targetable里,看代码:

[java] view plaincopy

public class Source {  

  •   
  •     public void method1() {  
  •         System.out.println("this is original method!");  
  •     }  
  • }  
[java] view plaincopy

public interface Targetable {  

  •   
  •     /* 与原类中的方法相同 */  
  •     public void method1();  
  •   
  •     /* 新类的方法 */  
  •     public void method2();  
  • }  
[java] view plaincopy

public class Adapter extends Source implements Targetable {  

  •   
  •     @Override  
  •     public void method2() {  
  •         System.out.println("this is the targetable method!");  
  •     }  
  • }  

 

view plaincopy

public class AdapterTest {  

  •   
  •     public static void main(String[] args) {  
  •         Targetable target = new Adapter();  
  •         target.method1();  
  •         target.method2();  
  •     }  
  • }  

this is original method!
this is the targetable method!

对象的适配器模式

 

 

view plaincopy

public class Wrapper implements Targetable {  

  •   
  •     private Source source;  
  •       
  •     public Wrapper(Source source){  
  •         super();  
  •         this.source = source;  
  •     }  
  •     @Override  
  •     public void method2() {  
  •         System.out.println("this is the targetable method!");  
  •     }  
  •   
  •     @Override  
  •     public void method1() {  
  •         source.method1();  
  •     }  
  • }  

 

view plaincopy

public class AdapterTest {  

  •   
  •     public static void main(String[] args) {  
  •         Source source = new Source();  
  •         Targetable target = new Wrapper(source);  
  •         target.method1();  
  •         target.method2();  
  •     }  
  • }  

第三种适配器模式是接口的适配器模式,接口的适配器是这样的:有时我们写的一个接口中有多个抽象方法,当我们写该接口的实现类时,必须实现该接口的所有方法,这明显有时比较浪费,因为并不是所有的方法都是我们需要的,有时只需要某一些,此处为了解决这个问题,我们引入了接口的适配器模式,借助于一个抽象类,该抽象类实现了该接口,实现了所有的方法,而我们不和原始的接口打交道,只和该抽象类取得联系,所以我们写一个类,继承该抽象类,重写我们需要的方法就行。看一下类图:

这个很好理解,在实际开发中,我们也常会遇到这种接口中定义了太多的方法,以致于有时我们在一些实现类中并不是都需要。看代码:

[java] view plaincopy

public interface Sourceable {  

  •       
  •     public void method1();  
  •     public void method2();  
  • }  

 

view plaincopy

public abstract class Wrapper2 implements Sourceable{  

  •       
  •     public void method1(){}  
  •     public void method2(){}  
  • }  
[java] view plaincopy

public class SourceSub1 extends Wrapper2 {  

  •     public void method1(){  
  •         System.out.println("the sourceable interface's first Sub1!");  
  •     }  
  • }  
[java] view plaincopy

public class SourceSub2 extends Wrapper2 {  

  •     public void method2(){  
  •         System.out.println("the sourceable interface's second Sub2!");  
  •     }  
  • }  
[java] view plaincopy

public class WrapperTest {  

  •   
  •     public static void main(String[] args) {  
  •         Sourceable source1 = new SourceSub1();  
  •         Sourceable source2 = new SourceSub2();  
  •           
  •         source1.method1();  
  •         source1.method2();  
  •         source2.method1();  
  •         source2.method2();  
  •     }  
  • }  

the sourceable interface's first Sub1!
the sourceable interface's second Sub2!

 讲了这么多,总结一下三种适配器模式的应用场景:

对象的适配器模式:当希望将一个对象转换成满足另一个新接口的对象时,可以创建一个Wrapper类,持有原类的一个实例,在Wrapper类的方法中,调用实例的方法就行。

7、装饰模式(Decorator)

 

view plaincopy

public interface Sourceable {  

  •     public void method();  
  • }  
[java] view plaincopy

public class Source implements Sourceable {  

  •   
  •     @Override  
  •     public void method() {  
  •         System.out.println("the original method!");  
  •     }  
  • }  
[java] view plaincopy

public class Decorator implements Sourceable {  

  •   
  •     private Sourceable source;  
  •       
  •     public Decorator(Sourceable source){  
  •         super();  
  •         this.source = source;  
  •     }  
  •     @Override  
  •     public void method() {  
  •         System.out.println("before decorator!");  
  •         source.method();  
  •         System.out.println("after decorator!");  
  •     }  
  • }  

 

view plaincopy

public class DecoratorTest {  

  •   
  •     public static void main(String[] args) {  
  •         Sourceable source = new Source();  
  •         Sourceable obj = new Decorator(source);  
  •         obj.method();  
  •     }  
  • }  

before decorator!
the original method!
after decorator!

1、需要扩展一个类的功能。

缺点:产生过多相似的对象,不易排错!

其实每个模式名称就表明了该模式的作用,代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候回去找中介,为什么呢?因为你对该地区房屋的信息掌握的不够全面,希望找一个更熟悉的人去帮你做,此处的代理就是这个意思。再如我们有的时候打官司,我们需要请律师,因为律师在法律方面有专长,可以替我们进行操作,表达我们的想法。先来看看关系图:

 

 

view plaincopy

public interface Sourceable {  

  •     public void method();  
  • }  
[java] view plaincopy

public class Source implements Sourceable {  

  •   
  •     @Override  
  •     public void method() {  
  •         System.out.println("the original method!");  
  •     }  
  • }  
[java] view plaincopy

public class Proxy implements Sourceable {  

  •   
  •     private Source source;  
  •     public Proxy(){  
  •         super();  
  •         this.source = new Source();  
  •     }  
  •     @Override  
  •     public void method() {  
  •         before();  
  •         source.method();  
  •         atfer();  
  •     }  
  •     private void atfer() {  
  •         System.out.println("after proxy!");  
  •     }  
  •     private void before() {  
  •         System.out.println("before proxy!");  
  •     }  
  • }  

 

view plaincopy

public class ProxyTest {  

  •   
  •     public static void main(String[] args) {  
  •         Sourceable source = new Proxy();  
  •         source.method();  
  •     }  
  •   
  • }  

before proxy!
the original method!
after proxy!

如果已有的方法在使用的时候需要对原有的方法进行改进,此时有两种办法:

2、就是采用一个代理类调用原有的方法,且对产生的结果进行控制。这种方法就是代理模式。

9、外观模式(Facade)

spring一样,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口,看下类图:(我们以一个计算机的启动过程为例)

我们先看下实现类:

[java] view plaincopy

public class CPU {  

  •       
  •     public void startup(){  
  •         System.out.println("cpu startup!");  
  •     }  
  •       
  •     public void shutdown(){  
  •         System.out.println("cpu shutdown!");  
  •     }  
  • }  
[java] view plaincopy

public class Memory {  

  •       
  •     public void startup(){  
  •         System.out.println("memory startup!");  
  •     }  
  •       
  •     public void shutdown(){  
  •         System.out.println("memory shutdown!");  
  •     }  
  • }  
[java] view plaincopy

public class Disk {  

  •       
  •     public void startup(){  
  •         System.out.println("disk startup!");  
  •     }  
  •       
  •     public void shutdown(){  
  •         System.out.println("disk shutdown!");  
  •     }  
  • }  
[java] view plaincopy

public class Computer {  

  •     private CPU cpu;  
  •     private Memory memory;  
  •     private Disk disk;  
  •       
  •     public Computer(){  
  •         cpu = new CPU();  
  •         memory = new Memory();  
  •         disk = new Disk();  
  •     }  
  •       
  •     public void startup(){  
  •         System.out.println("start the computer!");  
  •         cpu.startup();  
  •         memory.startup();  
  •         disk.startup();  
  •         System.out.println("start computer finished!");  
  •     }  
  •       
  •     public void shutdown(){  
  •         System.out.println("begin to close the computer!");  
  •         cpu.shutdown();  
  •         memory.shutdown();  
  •         disk.shutdown();  
  •         System.out.println("computer closed!");  
  •     }  
  • }  

 

view plaincopy

public class User {  

  •   
  •     public static void main(String[] args) {  
  •         Computer computer = new Computer();  
  •         computer.startup();  
  •         computer.shutdown();  
  •     }  
  • }  

start the computer!
cpu startup!
memory startup!
disk startup!
start computer finished!
begin to close the computer!
cpu shutdown!
memory shutdown!
disk shutdown!
computer closed!

10、桥接模式(Bridge)

数据库的时候,在各个数据库之间进行切换,基本不需要动太多的代码,甚至丝毫不用动,原因就是JDBC提供统一接口,每个数据库提供各自的实现,用一个叫做数据库驱动的程序来桥接就行了。我们来看看关系图:

实现代码:

 

view plaincopy

public interface Sourceable {  

  •     public void method();  
  • }  

 

view plaincopy

public class SourceSub1 implements Sourceable {  

  •   
  •     @Override  
  •     public void method() {  
  •         System.out.println("this is the first sub!");  
  •     }  
  • }  
[java] view plaincopy

public class SourceSub2 implements Sourceable {  

  •   
  •     @Override  
  •     public void method() {  
  •         System.out.println("this is the second sub!");  
  •     }  
  • }  

 

view plaincopy

public abstract class Bridge {  

  •     private Sourceable source;  
  •   
  •     public void method(){  
  •         source.method();  
  •     }  
  •       
  •     public Sourceable getSource() {  
  •         return source;  
  •     }  
  •   
  •     public void setSource(Sourceable source) {  
  •         this.source = source;  
  •     }  
  • }  
[java] view plaincopy

public class MyBridge extends Bridge {  

  •     public void method(){  
  •         getSource().method();  
  •     }  
  • }  

 

view plaincopy

public class BridgeTest {  

  •       
  •     public static void main(String[] args) {  
  •           
  •         Bridge bridge = new MyBridge();  
  •           
  •         /*调用第一个对象*/  
  •         Sourceable source1 = new SourceSub1();  
  •         bridge.setSource(source1);  
  •         bridge.method();  
  •           
  •         /*调用第二个对象*/  
  •         Sourceable source2 = new SourceSub2();  
  •         bridge.setSource(source2);  
  •         bridge.method();  
  •     }  
  • }  

this is the first sub!
this is the second sub!

组合模式有时又叫部分-整体模式在处理类似树形结构的问题时比较方便,看看关系图:

直接来看代码:

[java] view plaincopy

public class TreeNode {  

  •       
  •     private String name;  
  •     private TreeNode parent;  
  •     private Vector<TreeNode> children = new Vector<TreeNode>();  
  •       
  •     public TreeNode(String name){  
  •         this.name = name;  
  •     }  
  •   
  •     public String getName() {  
  •         return name;  
  •     }  
  •   
  •     public void setName(String name) {  
  •         this.name = name;  
  •     }  
  •   
  •     public TreeNode getParent() {  
  •         return parent;  
  •     }  
  •   
  •     public void setParent(TreeNode parent) {  
  •         this.parent = parent;  
  •     }  
  •       
  •     //添加孩子节点  
  •     public void add(TreeNode node){  
  •         children.add(node);  
  •     }  
  •       
  •     //删除孩子节点  
  •     public void remove(TreeNode node){  
  •         children.remove(node);  
  •     }  
  •       
  •     //取得孩子节点  
  •     public Enumeration<TreeNode> getChildren(){  
  •         return children.elements();  
  •     }  
  • }  
[java] view plaincopy

public class Tree {  

  •   
  •     TreeNode root = null;  
  •   
  •     public Tree(String name) {  
  •         root = new TreeNode(name);  
  •     }  
  •   
  •     public static void main(String[] args) {  
  •         Tree tree = new Tree("A");  
  •         TreeNode nodeB = new TreeNode("B");  
  •         TreeNode nodeC = new TreeNode("C");  
  •           
  •         nodeB.add(nodeC);  
  •         tree.root.add(nodeB);  
  •         System.out.println("build the tree finished!");  
  •     }  
  • }  

12、享元模式(Flyweight)

看个例子:

看下数据库连接池的代码:

[java] view plaincopy

public class ConnectionPool {  

  •       
  •     private Vector<Connection> pool;  
  •       
  •     /*公有属性*/  
  •     private String url = "jdbc:mysql://localhost:3306/test";  
  •     private String username = "root";  
  •     private String password = "root";  
  •     private String driverClassName = "com.mysql.jdbc.Driver";  
  •   
  •     private int poolSize = 100;  
  •     private static ConnectionPool instance = null;  
  •     Connection conn = null;  
  •   
  •     /*构造方法,做一些初始化工作*/  
  •     private ConnectionPool() {  
  •         pool = new Vector<Connection>(poolSize);  
  •   
  •         for (int i = 0; i < poolSize; i++) {  
  •             try {  
  •                 Class.forName(driverClassName);  
  •                 conn = DriverManager.getConnection(url, username, password);  
  •                 pool.add(conn);  
  •             } catch (ClassNotFoundException e) {  
  •                 e.printStackTrace();  
  •             } catch (SQLException e) {  
  •                 e.printStackTrace();  
  •             }  
  •         }  
  •     }  
  •   
  •     /* 返回连接到连接池 */  
  •     public synchronized void release() {  
  •         pool.add(conn);  
  •     }  
  •   
  •     /* 返回连接池中的一个数据库连接 */  
  •     public synchronized Connection getConnection() {  
  •         if (pool.size() > 0) {  
  •             Connection conn = pool.get(0);  
  •             pool.remove(conn);  
  •             return conn;  
  •         } else {  
  •             return null;  
  •         }  
  •     }  
  • }  
 
通过连接池的管理,实现了数据库连接的共享,不需要每一次都重新创建连接,节省了数据库重新创建的开销,提升了系统的性能!本章讲解了7种结构型模式,因为篇幅的问题,剩下的11种行为型模式,

 

 

第一类:通过父类与子类的关系进行实现。第二类:两个类之间。第三类:类的状态。第四类:通过中间类

13、策略模式(strategy)

首先统一接口:

[java] view plaincopy

public interface ICalculator {  

  •     public int calculate(String exp);  
  • }  

 

view plaincopy

public abstract class AbstractCalculator {  

  •       
  •     public int[] split(String exp,String opt){  
  •         String array[] = exp.split(opt);  
  •         int arrayInt[] = new int[2];  
  •         arrayInt[0] = Integer.parseInt(array[0]);  
  •         arrayInt[1] = Integer.parseInt(array[1]);  
  •         return arrayInt;  
  •     }  
  • }  

 

view plaincopy

public class Plus extends AbstractCalculator implements ICalculator {  

  •   
  •     @Override  
  •     public int calculate(String exp) {  
  •         int arrayInt[] = split(exp,"\+");  
  •         return arrayInt[0]+arrayInt[1];  
  •     }  
  • }  
[java] view plaincopy

public class Minus extends AbstractCalculator implements ICalculator {  

  •   
  •     @Override  
  •     public int calculate(String exp) {  
  •         int arrayInt[] = split(exp,"-");  
  •         return arrayInt[0]-arrayInt[1];  
  •     }  
  •   
  • }  
[java] view plaincopy

public class Multiply extends AbstractCalculator implements ICalculator {  

  •   
  •     @Override  
  •     public int calculate(String exp) {  
  •         int arrayInt[] = split(exp,"\*");  
  •         return arrayInt[0]*arrayInt[1];  
  •     }  
  • }  

 

view plaincopy

public class StrategyTest {  

  •   
  •     public static void main(String[] args) {  
  •         String exp = "2+8";  
  •         ICalculator cal = new Plus();  
  •         int result = cal.calculate(exp);  
  •         System.out.println(result);  
  •     }  
  • }  

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

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

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

[java] view plaincopy

public abstract class AbstractCalculator {  

  •       
  •     /*主方法,实现对本类其它方法的调用*/  
  •     public final int calculate(String exp,String opt){  
  •         int array[] = split(exp,opt);  
  •         return calculate(array[0],array[1]);  
  •     }  
  •       
  •     /*被子类重写的方法*/  
  •     abstract public int calculate(int num1,int num2);  
  •       
  •     public int[] split(String exp,String opt){  
  •         String array[] = exp.split(opt);  
  •         int arrayInt[] = new int[2];  
  •         arrayInt[0] = Integer.parseInt(array[0]);  
  •         arrayInt[1] = Integer.parseInt(array[1]);  
  •         return arrayInt;  
  •     }  
  • }  
[java] view plaincopy

public class Plus extends AbstractCalculator {  

  •   
  •     @Override  
  •     public int calculate(int num1,int num2) {  
  •         return num1 + num2;  
  •     }  
  • }  

 

view plaincopy

public class StrategyTest {  

  •   
  •     public static void main(String[] args) {  
  •         String exp = "8+8";  
  •         AbstractCalculator cal = new Plus();  
  •         int result = cal.calculate(exp, "\+");  
  •         System.out.println(result);  
  •     }  
  • }  

15、观察者模式(Observer)

一个Observer接口:

[java] view plaincopy

public interface Observer {  

  •     public void update();  
  • }  

 

view plaincopy

public class Observer1 implements Observer {  

  •   
  •     @Override  
  •     public void update() {  
  •         System.out.println("observer1 has received!");  
  •     }  
  • }  
[java] view plaincopy

public class Observer2 implements Observer {  

  •   
  •     @Override  
  •     public void update() {  
  •         System.out.println("observer2 has received!");  
  •     }  
  •   
  • }  

 

view plaincopy

public interface Subject {  

  •       
  •     /*增加观察者*/  
  •     public void add(Observer observer);  
  •       
  •     /*删除观察者*/  
  •     public void del(Observer observer);  
  •       
  •     /*通知所有的观察者*/  
  •     public void notifyObservers();  
  •       
  •     /*自身的操作*/  
  •     public void operation();  
  • }  
[java] view plaincopy

public abstract class AbstractSubject implements Subject {  

  •   
  •     private Vector<Observer> vector = new Vector<Observer>();  
  •     @Override  
  •     public void add(Observer observer) {  
  •         vector.add(observer);  
  •     }  
  •   
  •     @Override  
  •     public void del(Observer observer) {  
  •         vector.remove(observer);  
  •     }  
  •   
  •     @Override  
  •     public void notifyObservers() {  
  •         Enumeration<Observer> enumo = vector.elements();  
  •         while(enumo.hasMoreElements()){  
  •             enumo.nextElement().update();  
  •         }  
  •     }  
  • }  
[java] view plaincopy

public class MySubject extends AbstractSubject {  

  •   
  •     @Override  
  •     public void operation() {  
  •         System.out.println("update self!");  
  •         notifyObservers();  
  •     }  
  •   
  • }  

 

view plaincopy

public class ObserverTest {  

  •   
  •     public static void main(String[] args) {  
  •         Subject sub = new MySubject();  
  •         sub.add(new Observer1());  
  •         sub.add(new Observer2());  
  •           
  •         sub.operation();  
  •     }  
  •   
  • }  

update self!
observer1 has received!
observer2 has received!

根据关系图,新建项目,自己写代码(或者参考我的代码),按照总体思路走一遍,这样才能体会它的思想,理解起来容易! 

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

 

两个接口:

[java] view plaincopy

public interface Collection {  

  •       
  •     public Iterator iterator();  
  •       
  •     /*取得集合元素*/  
  •     public Object get(int i);  
  •       
  •     /*取得集合大小*/  
  •     public int size();  
  • }  
[java] view plaincopy

public interface Iterator {  

  •     //前移  
  •     public Object previous();  
  •       
  •     //后移  
  •     public Object next();  
  •     public boolean hasNext();  
  •       
  •     //取得第一个元素  
  •     public Object first();  
  • }  

 

view plaincopy

public class MyCollection implements Collection {  

  •   
  •     public String string[] = {"A","B","C","D","E"};  
  •     @Override  
  •     public Iterator iterator() {  
  •         return new MyIterator(this);  
  •     }  
  •   
  •     @Override  
  •     public Object get(int i) {  
  •         return string[i];  
  •     }  
  •   
  •     @Override  
  •     public int size() {  
  •         return string.length;  
  •     }  
  • }  
[java] view plaincopy

public class MyIterator implements Iterator {  

  •   
  •     private Collection collection;  
  •     private int pos = -1;  
  •       
  •     public MyIterator(Collection collection){  
  •         this.collection = collection;  
  •     }  
  •       
  •     @Override  
  •     public Object previous() {  
  •         if(pos > 0){  
  •             pos--;  
  •         }  
  •         return collection.get(pos);  
  •     }  
  •   
  •     @Override  
  •     public Object next() {  
  •         if(pos<collection.size()-1){  
  •             pos++;  
  •         }  
  •         return collection.get(pos);  
  •     }  
  •   
  •     @Override  
  •     public boolean hasNext() {  
  •         if(pos<collection.size()-1){  
  •             return true;  
  •         }else{  
  •             return false;  
  •         }  
  •     }  
  •   
  •     @Override  
  •     public Object first() {  
  •         pos = 0;  
  •         return collection.get(pos);  
  •     }  
  •   
  • }  

 

view plaincopy

public class Test {  

  •   
  •     public static void main(String[] args) {  
  •         Collection collection = new MyCollection();  
  •         Iterator it = collection.iterator();  
  •           
  •         while(it.hasNext()){  
  •             System.out.println(it.next());  
  •         }  
  •     }  
  • }  

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

 

 

 

view plaincopy

public interface Handler {  

  •     public void operator();  
  • }  
[java] view plaincopy

public abstract class AbstractHandler {  

  •       
  •     private Handler handler;  
  •   
  •     public Handler getHandler() {  
  •         return handler;  
  •     }  
  •   
  •     public void setHandler(Handler handler) {  
  •         this.handler = handler;  
  •     }  
  •       
  • }  
[java] view plaincopy

public class MyHandler extends AbstractHandler implements Handler {  

  •   
  •     private String name;  
  •   
  •     public MyHandler(String name) {  
  •         this.name = name;  
  •     }  
  •   
  •     @Override  
  •     public void operator() {  
  •         System.out.println(name+"deal!");  
  •         if(getHandler()!=null){  
  •             getHandler().operator();  
  •         }  
  •     }  
  • }  
[java] view plaincopy

public class Test {  

  •   
  •     public static void main(String[] args) {  
  •         MyHandler h1 = new MyHandler("h1");  
  •         MyHandler h2 = new MyHandler("h2");  
  •         MyHandler h3 = new MyHandler("h3");  
  •   
  •         h1.setHandler(h2);  
  •         h2.setHandler(h3);  
  •   
  •         h1.operator();  
  •     }  
  • }  

h1deal!
h2deal!
h3deal!

 18、命令模式(Command)

 

view plaincopy

public interface Command {  

  •     public void exe();  
  • }  
[java] view plaincopy

public class MyCommand implements Command {  

  •   
  •     private Receiver receiver;  
  •       
  •     public MyCommand(Receiver receiver) {  
  •         this.receiver = receiver;  
  •     }  
  •   
  •     @Override  
  •     public void exe() {  
  •         receiver.action();  
  •     }  
  • }  
[java] view plaincopy

public class Receiver {  

  •     public void action(){  
  •         System.out.println("command received!");  
  •     }  
  • }  
[java] view plaincopy

public class Invoker {  

  •       
  •     private Command command;  
  •       
  •     public Invoker(Command command) {  
  •         this.command = command;  
  •     }  
  •   
  •     public void action(){  
  •         command.exe();  
  •     }  
  • }  
[java] view plaincopy

public class Test {  

  •   
  •     public static void main(String[] args) {  
  •         Receiver receiver = new Receiver();  
  •         Command cmd = new MyCommand(receiver);  
  •         Invoker invoker = new Invoker(cmd);  
  •         invoker.action();  
  •     }  
  • }  

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

19、备忘录模式(Memento)

 

view plaincopy

public class Original {  

  •       
  •     private String value;  
  •       
  •     public String getValue() {  
  •         return value;  
  •     }  
  •   
  •     public void setValue(String value) {  
  •         this.value = value;  
  •     }  
  •   
  •     public Original(String value) {  
  •         this.value = value;  
  •     }  
  •   
  •     public Memento createMemento(){  
  •         return new Memento(value);  
  •     }  
  •       
  •     public void restoreMemento(Memento memento){  
  •         this.value = memento.getValue();  
  •     }  
  • }  
[java] view plaincopy

public class Memento {  

  •       
  •     private String value;  
  •   
  •     public Memento(String value) {  
  •         this.value = value;  
  •     }  
  •   
  •     public String getValue() {  
  •         return value;  
  •     }  
  •   
  •     public void setValue(String value) {  
  •         this.value = value;  
  •     }  
  • }  
[java] view plaincopy

public class Storage {  

  •       
  •     private Memento memento;  
  •       
  •     public Storage(Memento memento) {  
  •         this.memento = memento;  
  •     }  
  •   
  •     public Memento getMemento() {  
  •         return memento;  
  •     }  
  •   
  •     public void setMemento(Memento memento) {  
  •         this.memento = memento;  
  •     }  
  • }  

 

view plaincopy

public class Test {  

  •   
  •     public static void main(String[] args) {  
  •           
  •         // 创建原始类  
  •         Original origi = new Original("egg");  
  •   
  •         // 创建备忘录  
  •         Storage storage = new Storage(origi.createMemento());  
  •   
  •         // 修改原始类的状态  
  •         System.out.println("初始化状态为:" + origi.getValue());  
  •         origi.setValue("niu");  
  •         System.out.println("修改后的状态为:" + origi.getValue());  
  •   
  •         // 回复原始类的状态  
  •         origi.restoreMemento(storage.getMemento());  
  •         System.out.println("恢复后的状态为:" + origi.getValue());  
  •     }  
  • }  

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

20、状态模式(State)

 

[java] view plaincopy

package com.xtfggef.dp.state;  

  •   
  • /** 
  •  * 状态类的核心类 
  •  * 2012-12-1 
  •  * @author erqing 
  •  * 
  •  */  
  • public class State {  
  •       
  •     private String value;  
  •       
  •     public String getValue() {  
  •         return value;  
  •     }  
  •   
  •     public void setValue(String value) {  
  •         this.value = value;  
  •     }  
  •   
  •     public void method1(){  
  •         System.out.println("execute the first opt!");  
  •     }  
  •       
  •     public void method2(){  
  •         System.out.println("execute the second opt!");  
  •     }  
  • }  
[java] view plaincopy

package com.xtfggef.dp.state;  

  •   
  • /** 
  •  * 状态模式的切换类   2012-12-1 
  •  * @author erqing 
  •  *  
  •  */  
  • public class Context {  
  •   
  •     private State state;  
  •   
  •     public Context(State state) {  
  •         this.state = state;  
  •     }  
  •   
  •     public State getState() {  
  •         return state;  
  •     }  
  •   
  •     public void setState(State state) {  
  •         this.state = state;  
  •     }  
  •   
  •     public void method() {  
  •         if (state.getValue().equals("state1")) {  
  •             state.method1();  
  •         } else if (state.getValue().equals("state2")) {  
  •             state.method2();  
  •         }  
  •     }  
  • }  
 

 

[java] view plaincopy
public class Test {  
  •   
  •     public static void main(String[] args) {  
  •           
  •         State state = new State();  
  •         Context context = new Context(state);  
  •           
  •         //设置第一种状态  
  •         state.setValue("state1");  
  •         context.method();  
  •           
  •         //设置第二种状态  
  •         state.setValue("state2");  
  •         context.method();  
  •     }  
  • }  
 

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

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

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

 

[java] view plaincopy
public interface Visitor {  
  •     public void visit(Subject sub);  
  • }  
[java] view plaincopy

public class MyVisitor implements Visitor {  

  •   
  •     @Override  
  •     public void visit(Subject sub) {  
  •         System.out.println("visit the subject:"+sub.getSubject());  
  •     }  
  • }  
 
[java] view plaincopy

public interface Subject {  

  •     public void accept(Visitor visitor);  
  •     public String getSubject();  
  • }  
[java] view plaincopy

public class MySubject implements Subject {  

  •   
  •     @Override  
  •     public void accept(Visitor visitor) {  
  •         visitor.visit(this);  
  •     }  
  •   
  •     @Override  
  •     public String getSubject() {  
  •         return "love";  
  •     }  
  • }  
 

 

 

 

 

 

 

 

[java] view plaincopy
public class Test {  
  •   
  •     public static void main(String[] args) {  
  •           
  •         Visitor visitor = new MyVisitor();  
  •         Subject sub = new MySubject();  
  •         sub.accept(visitor);      
  •     }  
  • }  
 

 

 

 

 

 

 

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

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

 

[java] view plaincopy
public interface Mediator {  
  •     public void createMediator();  
  •     public void workAll();  
  • }  
[java] view plaincopy

public class MyMediator implements Mediator {  

  •   
  •     private User user1;  
  •     private User user2;  
  •       
  •     public User getUser1() {  
  •         return user1;  
  •     }  
  •   
  •     public User getUser2() {  
  •         return user2;  
  •     }  
  •   
  •     @Override  
  •     public void createMediator() {  
  •         user1 = new User1(this);  
  •         user2 = new User2(this);  
  •     }  
  •   
  •     @Override  
  •     public void workAll() {  
  •         user1.work();  
  •         user2.work();  
  •     }  
  • }  
[java] view plaincopy

public abstract class User {  

  •       
  •     private Mediator mediator;  
  •       
  •     public Mediator getMediator(){  
  •         return mediator;  
  •     }  
  •       
  •     public User(Mediator mediator) {  
  •         this.mediator = mediator;  
  •     }  
  •   
  •     public abstract void work();  
  • }  
[java] view plaincopy

public class User1 extends User {  

  •   
  •     public User1(Mediator mediator){  
  •         super(mediator);  
  •     }  
  •       
  •     @Override  
  •     public void work() {  
  •         System.out.println("user1 exe!");  
  •     }  
  • }  
[java] view plaincopy

public class User2 extends User {  

  •   
  •     public User2(Mediator mediator){  
  •         super(mediator);  
  •     }  
  •       
  •     @Override  
  •     public void work() {  
  •         System.out.println("user2 exe!");  
  •     }  
  • }  
 

 

 

 

 

 

 

 

[java] view plaincopy
public class Test {  
  •   
  •     public static void main(String[] args) {  
  •         Mediator mediator = new MyMediator();  
  •         mediator.createMediator();  
  •         mediator.workAll();  
  •     }  
  • }  
 

 

 

 

 

 

 

 

[java] view plaincopy
public interface Expression {  
  •     public int interpret(Context context);  
  • }  
[java] view plaincopy

public class Plus implements Expression {  

  •   
  •     @Override  
  •     public int interpret(Context context) {  
  •         return context.getNum1()+context.getNum2();  
  •     }  
  • }  
[java] view plaincopy

public class Minus implements Expression {  

  •   
  •     @Override  
  •     public int interpret(Context context) {  
  •         return context.getNum1()-context.getNum2();  
  •     }  
  • }  
[java] view plaincopy

public class Context {  

  •       
  •     private int num1;  
  •     private int num2;  
  •       
  •     public Context(int num1, int num2) {  
  •         this.num1 = num1;  
  •         this.num2 = num2;  
  •     }  
  •       
  •     public int getNum1() {  
  •         return num1;  
  •     }  
  •     public void setNum1(int num1) {  
  •         this.num1 = num1;  
  •     }  
  •     public int getNum2() {  
  •         return num2;  
  •     }  
  •     public void setNum2(int num2) {  
  •         this.num2 = num2;  
  •     }  
  •       
  •       
  • }  
[java] view plaincopy

public class Test {  

  •   
  •     public static void main(String[] args) {  
  •   
  •         // 计算9+2-8的值  
  •         int result = new Minus().interpret((new Context(new Plus()  
  •                 .interpret(new Context(92)), 8)));  
  •         System.out.println(result);  
  •     }  
  • }  
最后输出正确的结果:3。  

 基本就这样,解释器模式用来做各种各样的解释器,如正则表达式等的解释器等等!
设计模式基本就这么大概讲完了,总体感觉有点简略,的确,这么点儿篇幅,不足以对整个23种设计模式做全面的阐述,此处读者可将它作为一个理论基础去学习,通过这四篇博文,先基本有个概念,虽然我讲的有些简单,但基本都能说明问题及他们的特点,如果对哪一个感兴趣,可以继续深入研究!同时我也会不断更新,尽量补全遗

原文地址:https://www.cnblogs.com/mazhenyu/p/6480138.html