适配器模式

来源:互联网 发布:网络安全法考试单选 编辑:程序博客网 时间:2024/05/16 09:38

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

//提供双相电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();    } }
0 0