标签:设计模式
适配器模式:Adapter适配器模式类图:
以下程序模拟鸭子和火鸡的叫和飞的动作。假设你缺少鸭子对象,则将一个火鸡适配成一个鸭子,用火鸡冒充鸭子来使用。
1.定义鸭子接口
package net.dp.adapter.ducks; public interface Duck { public void quack(); public void fly(); }
package net.dp.adapter.ducks; public interface Turkey { public void gobble(); public void fly(); }
package net.dp.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"); } }4.实现火鸡的适配器
package net.dp.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(); } } }
5.测试类
package net.dp.adapter.ducks; public class DuckTestDrive { public static void main(String[] args) { WildTurkey turkey = new WildTurkey(); Duck turkeyAdapter = new TurkeyAdapter(turkey); testDuck(turkeyAdapter); } static void testDuck(Duck duck) { duck.quack(); duck.fly(); } }
标签:设计模式
原文地址:http://blog.csdn.net/liuchangqing123/article/details/43938595