设计模式系列之五:适配器模式
2017-02-21 14:36
232 查看
适配器模式属于结构型设计模式,主要应用于升级或改造旧系统时。所谓适配器按生活中的说法就是一个转接口,将原本不直接匹配的两个产品组合起来,类似于用iPhone手机充电器给android手机充电需要一个转换头,生活中这种例子随处可见。
适配器模式主要有三个组成部分,目标接口(Target),适配器(Adapter),适配对象(Adaptee)。
以上所采用的是类适配器,直接通过继承来实现,由于继承只能是单个继承,不够灵活,所以这种方法一般不如使用对象适配器。
得到的结果都是一样的
适配器模式主要有三个组成部分,目标接口(Target),适配器(Adapter),适配对象(Adaptee)。
package com.panda.adpter; public interface Target { void targ(); }
package com.panda.adpter; public class Adaptee { public void ada(){ System.out.println("适配对象方法!"); } }
package com.panda.adpter; public class Adapter extends Adaptee implements Target { @Override public void targ() { // TODO Auto-generated method stub super.ada(); } }
package com.panda.adpter; public class Client { public void test(Target t){ t.targ(); } public static void main(String[] args) { Client c = new Client(); // Adapter a = new Adapter(); Target t = new Adapter(); c.test(t); } }
以上所采用的是类适配器,直接通过继承来实现,由于继承只能是单个继承,不够灵活,所以这种方法一般不如使用对象适配器。
package com.panda.adpter; public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { super(); this.adaptee = adaptee; } @Override public void targ() { // TODO Auto-generated method stub adaptee.ada(); } }
package com.panda.adpter; public class Client { public void test(Target t){ t.targ(); } public static void main(String[] args) { Client c = new Client(); Adaptee a = new Adaptee(); Target t = new Adapter(a); c.test(t); } }
得到的结果都是一样的
相关文章推荐
- Android设计模式系列-适配器模式
- 深入理解JavaScript系列(39):设计模式之适配器模式详解
- 深入理解JavaScript系列(39):设计模式之适配器模式
- 设计模式系列七 适配器模式介绍
- Android设计模式系列-适配器模式
- Android设计模式系列(9)--SDK源码之适配器模式
- 深入理解JavaScript系列(39):设计模式之适配器模式
- Android设计模式系列-适配器模式
- Android设计模式系列(9)--SDK源码之适配器模式
- 设计模式系列-适配器模式
- 深入理解JavaScript系列(39):设计模式之适配器模式
- Android设计模式系列-适配器模式
- 极速理解设计模式系列:6.适配器模式(Adapter Pattern)
- Android设计模式系列--适配器模式
- 极速理解设计模式系列:6.适配器模式(Adapter Pattern)
- 【推荐】【老外写的iOS设计模式系列】第5部分 适配器模式
- 设计模式学习系列8 适配器模式
- 深入理解JavaScript系列(39):设计模式之适配器模式详解
- Android设计模式系列-适配器模式
- 深入理解JavaScript系列(39):设计模式之适配器模式