适配器模式,其实主要就是通过继承的方式,来保留原来的方法。
主要作用为:功能的扩展。
比如说:之前要在method方法中要存储日志,但是现在既要保留原来存储日志的功能,而且要新增加一个功能,是在原有存储日志功能的扩展。
1.
2.
3.
类的适配器主要是通过继承的方式实现的。
即:不修改原有类,新写一个类,继承原有类,然后在其中增加新方法,并且在新方法中调用之前的方法。实现功能的扩展。
示例代码:
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();
}
}