适配器模式

适配器模式,其实主要就是通过继承的方式,来保留原来的方法。

主要作用为:功能的扩展。
比如说:之前要在method方法中要存储日志,但是现在既要保留原来存储日志的功能,而且要新增加一个功能,是在原有存储日志功能的扩展。

1.
类的适配器主要是通过继承的方式实现的。
即:不修改原有类,新写一个类,继承原有类,然后在其中增加新方法,并且在新方法中调用之前的方法。实现功能的扩展。

示例代码:
package myDemo.adapter.WithClass;
public class Person {
	public void eat(){
		System.out.println("吃");
	}
}

package myDemo.adapter.WithClass;
public interface XiaoMing {
	public void cleanBeforeEat();
}

package myDemo.adapter.WithClass;
public class XiaoMingImpl extends Person implements XiaoMing {
	public void cleanBeforeEat() {
		System.out.println("先洗手");
		super.eat();
	}
}

package myDemo.adapter.WithClass;
public class DemoTest {
	public static void main(String[] args) {
		System.out.println("------------适配前");
		Person person = new Person();
		person.eat();
		System.out.println("------------适配后");
		XiaoMing xiaoMing = new XiaoMingImpl();
		xiaoMing.cleanBeforeEat();
		System.out.println("------------适配后调用适配前的方法");
		Person person2 = new XiaoMingImpl();
		person2.eat();
	}
}

2.
对象适配器不是用继承的方式来获取被适配类的方法
而是通过获取被适配类的对象的方式来获取其方法的:
具体代码如下:
package myDemo.adapter.WithObject;
public class Car {
	public void run(){
		System.out.println("I can run!");
	}
}


package myDemo.adapter.WithObject;
public class DaZhong {
	public Car car;
	public DaZhong(Car car) {
		this.car = car;
	}
	public void run(){
		this.car.run();
	}
}

3.
其实接口适配器可以说是多态的一种扩展。
接口的适配器主要是通过继承的方式来实现适配器模式的:
步骤为:
1.由一个抽象类实现接口的方法;
2.由适配器的类来继承抽象类,但是只重写抽象类的部分方法(自己想要适配的方法)
这样就可以实现接口适配器模式;
具体代码如下:
package myDemo.adapter.withInterface;
public interface Action {
	public void show1();
	public void show2();
	public void show3();
}

package myDemo.adapter.withInterface;
public abstract class AbstractAction implements Action{
	public void show1() {
		System.out.println("AbstractAction----show1");
	}
	public void show2() {
		System.out.println("AbstractAction----show2");
	}
	public void show3() {
		System.out.println("AbstractAction----show3");
	}
}

package myDemo.adapter.withInterface;
public class AdapterAction1 extends AbstractAction{
	public void show1() {
		System.out.println("AdapterAction1----show1");
	}
}

package myDemo.adapter.withInterface;
public class AdapterAction2 extends AbstractAction{
	public void show2() {
		System.out.println("AdapterAction2----show2");
	}
}

//测试类
package myDemo.adapter.withInterface;
public class DemoTest {
	public static void main(String[] args) {
		Action action1 = new AdapterAction1();
		action1.show1();
		action1.show2();
		action1.show3();
		System.out.println("---------------------------");
		Action action2 = new AdapterAction2();
		action2.show1();
		action2.show2();
		action2.show3();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值