MATLAB 2017-12-20
适配器模式分为两种:类适配器模式和对象适配器模式。废话不多说,直接上代码。
1、类适配器模式
public interface TargetInterface {
void method1();
void method2();
}
/**
* 需要被适配的类,该类要实现TargetInterface接口,但是不能被修改。
*
*/
class Adaptee {
public void method1() {
System.out.println("method1");
}
}
/**
* 适配器类
*
*/
class Adapter extends Adaptee implements TargetInterface {
public void method2() {
System.out.println("method2");
}
}
public class AdapterTest {
public static void main(String[] args) {
Adapter adapt = new Adapter();
adapt.method1();
adapt.method2();
}
}2、对象适配器模式
public interface TargetInterface {
void method1();
void method2();
}
/**
* 需要被适配的类,该类要实现TargetInterface接口,但是不能被修改。
*
*/
class Adaptee{
public void method1(){
System.out.println("method1");
}
}
/**
* 适配器类
*
*/
class Adapter implements TargetInterface {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void method1() {
this.adaptee.method1();
}
public void method2() {
System.out.println("method2");
}
}
public class AdapterTest {
public static void main(String[] args) {
Adapter adapt = new Adapter(new Adaptee());
adapt.method1();
adapt.method2();
}
} 前几篇介绍了设计模式的特性并且详细讲解了4种创建型模式,创建型模式是负责如何产生对象实例的,接下来讲讲结构型模式。结构型模式是解析类和对象的内部结构和外部组合,通过优化程序结构解决模块之间的耦合问题。