更多的可以参考我的博客,也在陆续更新ing
http://www.hspweb.cn/
适配器模式将一个类的接口,转换成客户期待的另一个接口。适配器让原本接口不兼容的类可以合作无间。
这个适配器充满着良好地OO设计原则:使用对象组合,以修改的接口包装被适配者:这种做法还有额外的缺点,那就是,被适配者的任何子类,都可以搭配着适配器使用。
下面以火鸡包装成一个鸭子为例子:
1.目录
2.package duck
①. Duck.java
package duck;
public interface Duck {
public void quack();
public void fly();
}
②.MallardDuck.java
package duck;
public class MallardDuck implements Duck{
@Override
public void quack() {
// TODO Auto-generated method stub
System.out.println("quack");
}
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("I am flying");
}
}
2.package turkey
①.Turkey.java
package turkey;
public interface Turkey {
public void gobble();
public void fly();
}
②.WildTurkey.java
package turkey;
public class WildTurkey implements Turkey{
@Override
public void gobble() {
// TODO Auto-generated method stub
System.out.println("Gobble gobble");
}
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("I am flying a short distance");
}
}
3.package adapter
①.TurkeyAdapter.java
package adapter;
import duck.Duck;
import turkey.Turkey;
public class TurkeyAdapter implements Duck{
Turkey turkey;
public TurkeyAdapter (Turkey turkey){
this.turkey=turkey;
}
@Override
public void quack() {
// TODO Auto-generated method stub
turkey.gobble();
}
@Override
public void fly() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
turkey.fly();
}
}
}
4.package test
①.test.java
package test;
import adapter.TurkeyAdapter;
import duck.Duck;
import duck.MallardDuck;
import turkey.WildTurkey;
public class Test {
public static void main(String[] args) {
MallardDuck duck=new MallardDuck();
WildTurkey turkey=new WildTurkey();
Duck turkeyAdapter=new TurkeyAdapter(turkey);
System.out.println("The Turkey says...");
turkey.gobble();
turkey.fly();
System.out.println("\nThe Duck says...");
testDuck(turkeyAdapter);
}
private static void testDuck(Duck duck) {
// TODO Auto-generated method stub
duck.quack();
duck.fly();
}
}