java设计模式(9) - 适配器模式

来源:互联网 发布:centos 7 锁屏 编辑:程序博客网 时间:2024/06/05 04:43
 概述:适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。
主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。

1. 类的适配器模式
        定义一个适配类,去实现这个接口,并继承这个需要适配的类。重写方法实现适配。
2.对象的适配器模式
       和类的适配类似,只不过使用装饰模式的方式去包含这个被适配的类,在重写的方法中调用这个配置的类的方法。
3.接口的适配器模式
        有时候一个接口有很多方法,但我们继承它时不并不需要实现它所有的方法,这时我们可以写一个抽象类去实现这个接口,用抽象类去实现接口所有的方法。 我们不再与直接与接口直接打交道,直接继承抽象类,复写必要的方法就行了。

/**
 * 目标接口
 * @author jiangwei
 *
 */
public interface Target {
 void method1();
 
 void method2();
}

/**
 * 希望被适配的类
 * @author jiangwei
 *
 */
public class Adaptee {
 public void method2() {
  System.out.println("我想被配置");
 }
}

/**
 * 类的适配
 * @author jiangwei
 *
 */
public class Adapter1 extends Adaptee implements Target{
 @Override
 public void method1() {
  System.out.println("自带的方法");
 }
 
}


/**
 * 对象的适配
 * @author jiangwei
 *
 */
public class Adapter2 implements Target{
 private Adaptee adaptee;
 
 public Adapter2() {
  adaptee = new Adaptee();
 }
 @Override
 public void method1() {
  System.out.println("自带的方法");
 }
 @Override
 public void method2() {
  adaptee.method2();
 }
}

0 0
原创粉丝点击