Posted by:richardluo
Posted on:2003-01-20 16:02
适配器模式的理解
public class window的软件
{
public void run(){
System.out.print("我运行在window上");
}
}
public class linux的软件
{
public void run1(){
System.out.print("我运行在linux上");
}
}
public class 适配器 extends window的软件
{
private linux的软件 软件1; //实际上是聚合的使用
public 适配器(linux的软件 软件变量)
{
this.软件1= 软件变量;
}
public void run()
{
软件1.run1();
}
}
客户段
public class test{
public static void main(String args[])
{
linux的软件 test1=new linux的软件();
适配器 test2=new 适配器(test1);
test2.run();
test2.run1();
}
Adapter 有所谓类形式的Adapter模式和实例类型的Adapter模式
所谓类形式的Adapter模式
public interface Target{
public void method1();
public void method2();
}
public class Adaptee{
public void method1(){
}
}
public class Adapter extends Adatpee implements Target
{
public void method2(){
}
}
理论上实现一个接口,就要实现接口所有的方法,可是Adapter没有实现method1,仔细一看是extends Adatpee,从Adatpee自动继承method1方法,哈哈,这就是GUI一写到实现listener接口的时候要实现一大堆方法,而extends ***Adapter 只要重写几个方法即可
所谓实例形式的Adapter模式
public interface Target{
public void method1();
public void method2();
}
public class Adaptee{
public void method1(){
}
}
public class Adapter implements Target
{
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee=adaptee;
}
public void method2(){
}
public void method1(){
}
}
实际上是把Adaptee传入来创造一个新对象Adapter,而整个这个Adapter类具备了Target的特征,而adaptee具有Adaptee的特征
比如说两个齿的插头需要插到三个口的插座里去,怎么办,找一个两头转三头的转换器,把两个头的插进去,整体就变成了一个三齿的插头,这里,插座它不是Target,三个齿的插头才是Target
而类形式的Adapter模式就是在两个齿的基础之上改造,让它多一个按纽,按一下是三个齿,再按一下是两个齿的。