您的位置:首页 > 编程语言 > Java开发

设计模式--结构模式--适配器模式--Java

2013-03-05 14:57 519 查看

适配器

intent--目的

•Convertthe interface of a class into another interface clients expect. Adapter letsclasses 
  work together that couldn't otherwise because of incompatibleinterfaces.
•将一个类的接口转换为客户端所期望的接口。
•Adapter模式使两个不兼容的两个接口可以一起工作。

Applicability---适用范围

•you want to use an existing class, and its interfacedoes not match the one you need.

•你想使用一个现有类,但是它的接口并不适用你的需求。

•you want to create a reusable class that cooperates withunrelated or unforeseen classes, that is, classes that don't   necessarily havecompatible interfaces.

•你想创建一个可重用的类,使那些没有关系或者不可预见的类协同工作。

•(object adapter only) you need to useseveral existing subclasses, but it's impractical to adapt their interface by subclassingevery one. An object adapter can adapt the interface of its parent class.

•(仅适用对象适配器)你想使用几个现存的子类,但是不可能对每一个都子类化以匹配它们的接口。一个对象适配器可以适配他的父类接口。

分类

•简单适配器
•对象适配器
•类适配器

简单适配器



JDK---Swing 中使用的简单适配器





对象适配器



下面这个例子是曾经做的j2se游戏局部代码,其中GameGraphics是游戏需求中所要求的接口,
但是jdk中的Graphics2D并不满足要求,又由于Graphics2D是一个具体的对象,我们也不需要
书写底层的绘制代码,所以以对象适配器的方式书写GameGraphicsBasic实现类来满足需求。



类适配器

类适配器主要是综合目标接口和现有的一个接口(不满足需求的接口)或者现有的一个类
(不满足需求的类)来实现出Adapter来便于客户端容易调用,对于客户端也隐藏了Adaptee
相关内容。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息