adapter(适配器模式)

适配器模式

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

适配器模式的二种实现方式

1、类的适配器模式
2、对象的适配器模式

1、类的适配器模式

在这里插入图片描述

  • 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
  • 需要适配的类(Adaptee):需要适配的类或适配者类。
  • 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。

代码实现

	// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
	class Adaptee {
		public void specificRequest() {
			System.out.println("被适配类具有 特殊功能...");
		}
	}
	 
	// 目标接口,或称为标准接口
	interface Target {
		public void request();
	}
	 
	// 具体目标类,只提供普通功能
	class ConcreteTarget implements Target {
		public void request() {
			System.out.println("普通类 具有 普通功能...");
		}
	}
	 
	// 适配器类,继承了被适配类,同时实现标准接口
	class Adapter extends Adaptee implements Target{
		public void request() {
			super.specificRequest();
		}
	}
	 
	// 测试类public class Client {
		public static void main(String[] args) {
			// 使用普通功能类
			Target concreteTarget = new ConcreteTarget();
			concreteTarget.request();
			
			// 使用特殊功能类,即适配类
			Target adapter = new Adapter();
			adapter.request();
		}
	}

运行结果:

	普通类 具有 普通功能...
	被适配类具有 特殊功能...

2、对象的适配器模式

在这里插入图片描述

代码实现

	// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
	public class Adaptee {
	    public void specificRequest() {
	        System.out.println("被适配类具有 特殊功能...");
	    }
	}
 
	// 目标接口,或称为标准接口
	public interface Target {
	
	    public void request();
	
	}
	// 具体目标类,只提供普通功能
	public class Adapter implements Target {
	
	    private Adaptee adaptee;
	
	    public Adapter(Adaptee adaptee) {
	        this.adapte e= adaptee;
	    }
	
	    @Override
	    public void request() {
	        adaptee.specificRequest();
	    }
	
	}
	// 测试类public class Client {
	public class Main {
	    public static void main(String[] args) {
	        Adaptee a = new Adaptee();
	        Target t = new Adapter(a);
	        t.request();
	    }
	}

输出

	被适配类具有 特殊功能...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值