Adapter patten 读书笔记

将一个类的接口,转换成客户期待的另一个接口。适配器让原本接口不兼容的类可以合作无间。

package pattern;
 interface Turkey {
   public void gobble();
   public void fly();   
}
class WildTurkey implements Turkey{
 public WildTurkey(){}
 public void gobble(){
  System.out.println("Gobble gobble");
 }
 public void fly(){
  System.out.println("i am flying a short distance");
 }
}
interface DuckInterface{
 public void quack();
 public void fly();
}
class MallardDuckinterface implements DuckInterface{
   public  MallardDuckinterface(){}
 public void quack(){
  System.out.println("quack");
 }
 public void fly(){
  System.out.println("i am fly");
 }
}
class TurkeyAdapter implements DuckInterface{
 Turkey turkey;
 public  TurkeyAdapter(Turkey turkey){
  turkey=turkey;
 }
 public void quack(){
  turkey.gobble();
 }
 public void fly(){
  for(int i=0;i<5;i++){
   turkey.fly();
  }
 }
}
class DuckAdapter implements Turkey{
 DuckInterface duckInterface;
 public void DuckAdapter(DuckInterface duckInterface){
  duckInterface=duckInterface;
 }
 public void gobble(){
  duckInterface.quack();
 }
 public void fly(){ 
   duckInterface.fly();
 }
}
package pattern;
public class DuckTestDrive {
 public static void main(String[] args) {
  DuckInterface duck=new MallardDuckinterface();
  WildTurkey turkey= new WildTurkey();
  
  DuckInterface turkeyAdapter=new TurkeyAdapter(turkey);
  System.out.println("The Turkey says...");
  turkey.gobble();
  turkey.fly();
  
  System.out.println("\n The Duck says...");
  testDuck(duck);
  
  System.out.println("\n The TurkeyAdapter says...");
  //testDuck(turkeyAdapter);
  turkeyAdapter.quack();
 }
 static void testDuck(DuckInterface duck){
  duck.quack();
  duck.fly();
 }
}

你可能感兴趣的:(读书)