适配器模式

适配器模式:
一个笔记本需要三相插口充电,然而现在只有双相电,需要为其创建适配器。

//提供双相电
public class Two(){
public void chargewithTwo(){
   System out println("用双相电充电")
  }
}
//三相电接口
public interface Three(){
   public void chargewithThree();
}
//适配器需要实现要转换的接口,并在构造函数中接收被转换的对象
public class TwoToThreeAdapter implements Three(){
    private Two Two;
    public TwoToThreeAdapter(Two two){
        this.two=two;
    }
    public void chargewithThree(){
        two.chargewithTwo();
    }
}
//笔记本
public class NoteBook(){
   private Three three;
   public NoteBook(Three three){
      this.three=three;
   }
   public  void charge(){
      three.chargewithThree();
   }
   public static  main(String[] args){
   //只提供了双相电
    Two two = new Two();
   //将双相电转换为三相的接口
    Three three  = new TwoToThreeAdapter(two);
   //为笔记本提供三相的接口
    NoteBook book = new NoteBook(three);
   //为笔记本充电
    book.charge(); 
   } 
}

你可能感兴趣的:(java)