Java中的适配器模式

适配器模式将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间

类适配器

要加入进来的类

package com.zw.mymaven;

//要加入进来的类
public class Adaptee {
	public void Adapteemethod() {
		System.out.println("我想要加入进来");
	}
}

通用接口

package com.zw.mymaven;

public interface Common {
	public void Commonmethod();
}
通用接口实现类

package com.zw.mymaven;

public class Commonimp implements Common {

	public void Commonmethod() {
		System.out.println("我是标准!");
	}

}

适配器

package com.zw.mymaven;

public class Adapt extends Adaptee implements Common {

	public void Commonmethod() {
		super.Adapteemethod();
	}

}

测试类

package com.zw.mymaven;

public class TestAdapt {

	public static void main(String[] args) {
		Common common = new Commonimp();
		common.Commonmethod();
		Common common2 = new Adapt();
		common2.Commonmethod();
	}

}

对象适配器

要加入进来的类、通用接口、通用接口都不用变

适配器

package com.zw.mymaven;

public class Adapt implements Common {
	private Adaptee adaptee;

	public Adapt(Adaptee adaptee) {
		this.adaptee = adaptee;
	}

	public void Commonmethod() {
		this.adaptee.Adapteemethod();
	}

}

测试类

package com.zw.mymaven;

public class TestAdapt {

	public static void main(String[] args) {
		Common common = new Commonimp();
		common.Commonmethod();
		Common common2 = new Adapt(new Adaptee());
		common2.Commonmethod();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值