四月16号 - 适配器模式
4月16号 -- 适配器模式
今天的任务:学习“适配器模式”
一、适配器(变压器)模式:
把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。
适配器模式分类:1、类的适配器模式(采用继承实现)2、对象适配器(采用对象组合方式实现)
1、类的适配器模式:
/** * 源,只有一个方法 */ public void run(){ System.out.println("跑"); }
/** *目标接口 */ public interface ITarget(){ //定义两个方法 void run(); void fly(); }
/** *继承源类,然后实现目标接口,从而实现类到接口的适配 */ public class Adapter excends Sources implements ITarget{ //实现源类没有的方法 public vpid fly(){ System.out.println("飞"); } }
public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ITarget target = new Adapter(); target .run(); target .fly(); }
输出结果
:跑
飞
从输出的结果可以看出,这就是适配器模式的作用
2、对象适配器
/** * 源对象,只有跑的功能 * */ public class Animal { public void run(){ System.out.println("跑"); } }
/** * 目标接口,即能跑,又能飞 * */ public interface ITarget { void run(); void fly(); }
/** * 通过构造函数引入源对象,并实现了目标的方法 * */ public class Adapter implements ITarget{ private Animal animal; //private animal animal2...可以适配多个对象 public Adapter(Animal animal){ this.animal = animal; } /** * 拓展几口要求的新方法 * */ public void fly(){ System.out.println("飞"); } /** * 使用源对象的方法 * */ public void run(){ this.animal.run(); }
public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ITarget itarget = new Adapter(new Animal()); itarget.run(); itarget.fly(); } }