设计模式之适配器模式
来源:互联网 发布:老虎板王能埋入数据吗 编辑:程序博客网 时间:2024/06/05 06:42
适配器模式定义:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
简单定义:封装对象,并提供不同的接口。
简单例子:
鸭子接口:
package headfirst.adapter.ducks;public interface Duck {public void quack();public void fly();}
具体鸭子:
package headfirst.adapter.ducks;public class MallardDuck implements Duck {public void quack() {System.out.println("Quack");} public void fly() {System.out.println("I'm flying");}}
火鸡接口:
package headfirst.adapter.ducks;public interface Turkey {public void gobble();public void fly();}
具体火鸡:
package headfirst.adapter.ducks;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");}}
将火鸡适配成鸭子:
package headfirst.adapter.ducks;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();}}}测试:
package headfirst.adapter.ducks;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();}}输出:
The Turkey says...Gobble gobbleI'm flying a short distanceThe Duck says...QuackI'm flyingThe TurkeyAdapter says...Gobble gobbleI'm flying a short distanceI'm flying a short distanceI'm flying a short distanceI'm flying a short distanceI'm flying a short distance
0 0
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器
- 设计模式 之 适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之--适配器模式.
- 第三篇——第二部分——第四文 配置SQL Server镜像——非域环境
- RTP 与RTCP 解释
- scala编程系列(1)-scala编程入门初步
- 数据接口-数据库数据,通过接口文件调用数据到不同的平台
- Android SDK下载和更新失败的…
- 设计模式之适配器模式
- GetClipBox与GetClientRect
- Android SDK开发包国内下载地址
- Android快速搭建模拟器环境另类方…
- Android SDK 2.3…
- LGD将在SID展示下一代曲面OLED面板
- Failed to open&n…
- emulator: Failed to&nb…
- 将 Shiro 作为应用的权限基础 一:shiro的整体架构