适配器模式
来源:互联网 发布:手机游戏作弊软件 编辑:程序博客网 时间:2024/05/16 17:25
一.前言
适配器,我们应该很常见才对,以前美版或者欧版的iphone充电时,需要一个充电器的转接头,那个转换头就是适配器。一句话适配器:使这样东西看起来像那样东西,就是适配器模式
二.很简单很简单的例子
一个很荒唐的需求,怎么让一只鸭子看起来像一只火鸡。
鸭子的接口以及绿头鸭类:
public interface Duck {public void quack();public void fly();}public class MallardDuck implements Duck {//呱呱叫public void quack() {System.out.println("Quack");} public void fly() {System.out.println("I'm flying");}}
火鸡的接口以及野生火鸡类:
public interface Turkey {public void gobble();public void fly();}public class WildTurkey implements Turkey {//咯咯叫public void gobble() {System.out.println("Gobble gobble");} public void fly() {System.out.println("I'm flying a short distance");}}
让火鸡看起来像一只鸭子,这时候就需要适配器,经过适配器后使火鸡看起来像一只鸭子:
public class TurkeyAdapter implements Duck {Turkey turkey; public TurkeyAdapter(Turkey turkey) {this.turkey = turkey;} public void quack() {turkey.gobble();} public void fly() {for(int i=0; i < 5; i++) {turkey.fly();}}}
下面是测试函数:
public class DuckTestDrive {public static void main(String[] args) {MallardDuck duck = new MallardDuck(); WildTurkey turkey = new WildTurkey();Duck turkeyAdapter = new TurkeyAdapter(turkey); System.out.println("The Turkey says...");turkey.gobble();turkey.fly(); System.out.println("\nThe Duck says...");testDuck(duck); System.out.println("\nThe TurkeyAdapter says...");testDuck(turkeyAdapter);} static void testDuck(Duck duck) {duck.quack();duck.fly();}}
三.真实世界的适配器
在java的集合中,如Stach,Hashtable,Vector的elements()方法都会返回一个Enumeration,而它和Iterator又很像在java中,迭代器和枚举类很像,怎样实现他们之间的适配,先看如下图:适配器EnumerationIterator,从枚举到迭代:
public class EnumerationIterator implements Iterator {Enumeration enumeration; public EnumerationIterator(Enumeration enumeration) {this.enumeration = enumeration;} public boolean hasNext() {return enumeration.hasMoreElements();} public Object next() {return enumeration.nextElement();} public void remove() {throw new UnsupportedOperationException();}}
测试函数:
public class IteratorEnumerationTestDrive {public static void main (String args[]) {ArrayList l = new ArrayList(Arrays.asList(args));Enumeration enumeration = new IteratorEnumeration(l.iterator());while (enumeration.hasMoreElements()) {System.out.println(enumeration.nextElement());}}}
以上
0 0
- 适配器及适配器模式
- 适配器及适配器模式
- 适配器模式(类适配器)
- 适配器模式(默认适配器)
- 适配器模式(对象适配器)
- 适配器模式-类适配器
- 适配器模式-对象适配器
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- hdu Bone Collector(背包)
- css布局之图片被拉伸问题
- win32 绘图
- 配置DHCP中继代理服务器
- OpenCL学习笔记(三):OpenCL安装,编程简介与helloworld
- 适配器模式
- PL/SQL 与oralce10g的连接问题
- Mybatis中传参包There is no getter for property named 'XXX' in 'class java.lang.String'
- MyBatis数据持久化(三)增删改查
- 深入了解MyBatis参数
- hdu1226 超级密码(bfs+余数判重)
- mysql新手学习
- Android中的Service 与 Thread 的区别?
- leetcode | String to Integer (atoi)