java设计模式之适配器模式

适配器模式:是指通过适配器类,将原有的类能够适配给第三方使用  该模式是很多设计模式的基础

类的适配器模式

  • 适配器模式是为了将某个类的接口转换成客户端期望的另一个接口表示
public class ClassAdapter {

	public void method1() {
		System.out.println("原来的方法");
	}
}


interface TargetAble {

	public void method1();

	void method2();

}


class Adapter extends ClassAdapter implements TargetAble {

	@Override
	public void method2() {
		System.out.println("this is a targertable method");
	}

}

class test{
	public static void main(String[]args){
		TargetAble targetAble=new Adapter();
		targetAble.method1();
		targetAble.method2();
	}
}


接口的适配器模式

  • 接口的适配器 写接口时 并不需要实现这个接口的所有类的场景 借助一个抽象类 该抽象类实现了该接口 实现了所有方法 不和原来的接口交接 继承接口类 实现该方法
public interface SourceAble{

	void method1();

	void method2();

}
public class SourceAble2 extends ObjectWrapper {
	@Override
	public void method2() {
		System.out.println("this is change method2");
	}


}
class SourceAble1 extends ObjectWrapper {
	@Override
	public void method1() {
		System.out.println("this is change method1");
	}

}


class test{
	public static void main(String[]args){
		SourceAble1 sourceAble1 = new SourceAble1();
		sourceAble1.method1();
		sourceAble1.method2();
		SourceAble2 sourceAble2 = new SourceAble2();
		sourceAble2.method1();
		sourceAble2.method2();
	}
}
public abstract class ObjectWrapper implements SourceAble{
	@Override
	public void method1() {
		System.out.println("this is original method1");
	}

	@Override
	public void method2() {
		System.out.println("this is original method2");
	}
}


对象的适配器模式

  • 对象的适配器模式 其他都不变 wrapper中持有source对象 通过该持有去调用原来的方法
public class ObjectAdapter {

	public static void main(String[] args) {
		TargetAble1 targetAble1=new Wrapper(new Source());
		targetAble1.method1();
		targetAble1.method2();
	}
}

class Source {

	public void method1() {

		System.out.println("this is a oringinal method");
	}

}


interface TargetAble1 {

	public void method1();
	public void method2();

}

class Wrapper implements TargetAble1{

	private Source source;

	public Wrapper(Source source) {
		this.source = source;
	}

	@Override
	public void method1() {
		source.method1();
	}

	@Override
	public void method2() {
		System.out.println("this is a target method");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值