适配器模式
package lp5; public interface Robot { //机器人接口 void cry(); void move(); }
package lp5; public class Application { public static void main (String args[]) { Dog dog=new Dog(); Robot dogRobot=new DogAdapter(dog); dogRobot.cry(); dogRobot.move(); Bird bird=new Bird(); Robot birdRobot=new BirdAdapter(bird); birdRobot.cry(); birdRobot.move(); } }
1 package lp5; 2 3 public class BirdAdapter implements Robot { 4 Bird bird; 5 public BirdAdapter(Bird bird) 6 { 7 this.bird=bird; 8 } 9 public void cry() 10 { 11 System.out.println("机器人模拟小鸟叫"); 12 bird.jiji(); 13 } 14 public void move() 15 { 16 System.out.println("机器人模拟小鸟飞"); 17 bird.fly(); 18 } 19 }
1 package lp5; 2 3 public class Dog { 4 public void wang() 5 { 6 System.out.println("小狗汪汪叫"); 7 } 8 public void run() 9 { 10 System.out.println("小狗快快跑"); 11 } 12 }
package lp5; public class DogAdapter implements Robot //DogAdapter小狗适配器类 { Dog dog; public DogAdapter(Dog dog) { this.dog=dog; } public void cry() { System.out.println("机器人模拟狗叫"); dog.wang(); } public void move() { System.out.println("机器人模拟狗跑"); dog.run(); } }
1 package lp5; 2 3 public class Bird { 4 public void jiji() 5 { 6 System.out.println("小鸟唧唧叫"); 7 } 8 public void fly() 9 { 10 System.out.println("小鸟慢慢飞"); 11 } 12 }
4 public static void main (String args[]) 5 { 6 Dog dog=new Dog(); 7 Robot dogRobot=new DogAdapter(dog); 8 dogRobot.cry(); 9 dogRobot.move(); 10 Bird bird=new Bird(); 11 Robot birdRobot=new BirdAdapter(bird); 12 birdRobot.cry(); 13 birdRobot.move(); 14 15 } 16 }