码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-适配器

时间:2015-04-08 10:50:49      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

 1 //定义鸭子接口
 2 public interface Duck {
 3     public void quack();
 4     public void fly();
 5 }
 6 //绿头鸭
 7 public class MallardDuck implements Duck{
 8 
 9     @Override
10     public void quack() {
11         // TODO Auto-generated method stub
12         System.out.println("duck ... quack .... quack");
13     }
14 
15     @Override
16     public void fly() {
17         // TODO Auto-generated method stub
18         System.out.println("duck ... fly ... fly");
19     }
20 
21 }
22 //定义火鸡接口
23 public interface Turkey {
24 
25     public void gobble();
26     public void fly();
27 }
28 //实现火鸡接口
29 public class WildTurkey implements Turkey{
30 
31     @Override
32     public void gobble() {
33         // TODO Auto-generated method stub
34         System.out.println("turkey ... gobble ... gobble");
35     }
36 
37     @Override
38     public void fly() {
39         // TODO Auto-generated method stub
40         System.out.println("turkey ... fly ... fly");
41     }
42 
43 }
44 //适配器,火鸡适配鸭子
45 public class TurkeyAdapter implements Duck{
46 
47     private Turkey mTurKey = null;
48     
49     public TurkeyAdapter(Turkey trukey){
50         mTurKey = trukey;
51     }
52     @Override
53     public void quack() {
54         // TODO Auto-generated method stub
55         if(mTurKey != null)
56             mTurKey.gobble();
57     }
58 
59     @Override
60     public void fly() {
61         // TODO Auto-generated method stub
62         if(mTurKey != null)
63             mTurKey.fly();
64     }
65 
66 }
67 public class Client {
68 
69     public static void main(String[] args) {
70         
71         MallardDuck duck = new MallardDuck();
72         
73         WildTurkey turkey = new WildTurkey();
74         
75         Duck turkeyAdapter = new TurkeyAdapter(turkey);
76         
77         testDuck(duck);
78         
79         testDuck(turkeyAdapter);
80     }
81     
82     static void testDuck(Duck duck){
83         if(duck != null){
84             duck.quack();
85             duck.fly();
86         }
87     }
88 }

 

设计模式-适配器

标签:

原文地址:http://www.cnblogs.com/jaden/p/4401615.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!