适配器模式(9)

适配器模式定义:将一个类的接口转换成另一种接口,让原本接口不兼容的类可以兼容。


现实中的例子:电源适配器(充电器)。由于设备的不同,输入电流电压有不同的标准,但是我国的家用电压是220V标准,所以需要经过电源适配器对电流电压进行转换才能安全充电。


适配器模式有两种形式:

  1. 对象适配器:适配器实现(implement)目标接口,且适配器类中有被适配对象的引用

  2. 类适配器:   适配器实现(implement)目标接口,适配器类直接继承被适配对象的类


适配器适配过程:从用户的角度看不到被适配者,是解耦的。

  1. 用户调用适配器转化出来的目标接口

  2. 适配器再调用被适配者的相关接口方法

  3. 用户收到反馈结果,感觉只是和目标接口交互


类图:对象适配器

 


代码示例:

1
2
3
4
5
6
7
8
//标准家用插座
public  class  NormalSocket {
     private  final  int   v =  220 ;
     public  int  out(){
         return  v;
     }
 
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//小米手机
public  class  MIMobile {
     private  final  String name =  "小米手机" ;
     private  byte  power;
     public  synchronized  void  charge(USBSocket electrictIn){
         if  (electrictIn== null ) {
             return  ;
         }
         if (electrictIn.out()== 5 ){
             new  Thread(){
                 @Override
                 public  void  run() {
                     while (power <  100 ){
                         power++;
                         System.out.println( "正在充电中,当前电量-------: " +power);
                         try  {
                             Thread.sleep( 1000 );
                         catch  (InterruptedException e) {
                             System.out.println( "充电器烧了,断开电源" );
                             return ;
                         }
                     }
                     System.out.println( "充电完成" );
                 }
             }.start();;
         } else  {
             System.out.println( "充电保护,断开充电源" );
         }
     }
}


1
2
3
4
5
//USB充电器
public  interface  USBSocket {
     public  int  out();
 
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//小米电源适配器
public  class  MIUSBSocketAdater  implements  USBSocket {
     private  NormalSocket normalSocket;
     public  MIUSBSocketAdater(NormalSocket normalSocket) {
         this .normalSocket = normalSocket;
     }
     
 
     @Override
     public  int  out() {
         if (normalSocket!= null ){
             return  5 ;
         } else  {
             System.out.println( "无电源输入" );
             return  0 ;
         }
         
     }
}


1
2
3
4
5
6
7
8
public  class  Main {
     public  static  void  main(String[] args) {
         MIMobile mobile =  new  MIMobile();
         NormalSocket normalSocket =  new  NormalSocket();
         MIUSBSocketAdater miusbSocketAdater =  new  MIUSBSocketAdater(normalSocket);
         mobile.charge(miusbSocketAdater);
     }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值