设计模式之适配器模式

mac2025-08-28  10

适配器模式(Adapter)

定义:

将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

特点:

示例:

/** * 期望的接口 */ public interface Target { void request(); } /** * 被适配者:具有特殊的方法 * 实际想用的类 */ public class Adaptee { public void specificRequest() { //适配者的行为 } } /** * 适配器:持有被适配者的引用,通过重写接口方法,实现适配 */ public class Adapter implements Target { private Adaptee mAdaptee;//持有适配者的引用 public Adapter(Adaptee adaptee) { mAdaptee = adaptee; } @Override public void request() { //适配重点,通过重写原接口方法,实现实际调用的转换,完成适配 mAdaptee.specificRequest(); } } /** * client端,需求是request接口 */ public class Client { private Target mTarget; public Client(Target target) { mTarget = target; } public void work() { mTarget.request(); } }

调用:

Adaptee adaptee = new Adaptee(); Target target = new Adapter(adaptee); Client client = new Client(target); client.work();
最新回复(0)