adapter和facade模式在Ajax中的应用-ajax技术教程
转载自:互联网 作者:cd3c.com
您正在看的ajax技术教程是:adapter和facade模式在Ajax中的应用。
一、 起因
在看《Ajax in action》的时候,看到它在介绍Adapter和Facade两种模式。由于目前Web开发的特色,特别是客户端Js脚本的开发,需要面对很多的变化和跨平台的挑战,所以,如果应用Adapter和Facade模式,将会非常有益于提高我们软件的可维护性,以及降低总体开发成本。
二、 什么是Adapter和Facade模式
1、 Adapter模式
1.1、定义:
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
1.2、解释:
Adapter模式所要解决的问题,就是接口不一致的问题。在实际的应用程序中,有的时候客户端(这里指调用方)想要调用的接口与实际上服务端(这里指被调用方)所提供的接口不一致。出现这种情况,我们可能会有两种选择,一种是修改调用方或者被调用方的接口,使之互相适应。另一种就是在调用方和被调用方之间加入一个Adapter,用其连接调用方和被调用方。
在Adapter模式里,Adapter所起的作用,就是一个接口适配器。一个Adapter类会实现(implements)调用方所期待的接口,并且在类中通过委派(delegate)来调用被调用方,从而实现两种不同接口的连接。
1.3、分类:
Adapter模式分为两种实现方式,一种是对象适配器(Object Adapters)和类适配器(Class Adapters)。其中对象适配器(Object Adapters)通过组合(composition)实现,而类适配器(Class Adapters)通过多继承实现。
1.4、关键点:
模式的关键点在于其意图。Adapter模式的意图很明显,就是为了使两个彼此不兼容的接口兼容,使一个本来并不是调用方所期待的接口看起来跟所期待的一样。
在《Head.First.Design.Patterns》这本书里,有一句话可以非常完美并且有趣的描述Adapter模式:
If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a duck adapter...
2、 Facade模式
2.1、定义:
The Facade Pattern provides a unified interface to a set of interfaces in subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
2.2、解释:
Facade模式的意图也是非常明显。有时候,我们的客户端(调用方)所调用的子系统(subsystem,被调用方)过于复杂。通常,调用方需要连续调用被调用方的N个接口才能完成某种特定的任务。每次调用方重复调用操作都非常繁琐,容易出错,所以本着DRY(Don’t Repeat Yourself)的原则,我们需要提炼出一些经常用到的操作组合成一个接口。这样,每次调用方执行该功能时,仅需要调用该Facade接口,便可以轻松执行某项特定任务。
2.3、作用
Facade模式的作用主要有两点:
1、 为一个太复杂的子系统(subsystem)提供一个统一的、简单的接口共调用方使用。通常需要DRY的接口都是使用率非常高,并且比较复杂的接口。将该接口提取出来,有益于简化工作,并且统一接口名称。
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] ... 下一篇 >>
