首页 > 其他分享 >设计模式(5)--适配器模式

设计模式(5)--适配器模式

时间:2023-01-06 10:33:16浏览次数:55  
标签:fly turkey -- Turkey 适配器 public Override 设计模式 void


  • 首先声明鸭子和火鸡的接口
package shipeiqi;
public interface Duck {
public void gaga();
public void fly();
}



public interface Turkey {
public void gogo();
public void fly();
}
  • 实现接口
public class RedDuck implements Duck {


@Override
public void gaga() {
System.out.println("Ga Ga");
}


@Override
public void fly() {
System.out.println("Fly a long distance");
}
}


public class RedTurkey implements Turkey {
@Override
public void gogo() {
System.out.println("Go Go");
}


@Override
public void fly() {
System.out.println("Fly a short distance");
}
}
  • 实现适配器
//用户看到的是鸭子
public class TurkeyAdapter implements Duck {
private Turkey turkey;
public TurkeyAdapter(Turkey turkey){
this.turkey = turkey;
}
@Override
public void gaga() {
turkey.gogo();
}


@Override
public void fly() {
for(int i = 0;i<3;i++){
turkey.fly();//因为鸭子飞的远,所以更改一部分
}
}
}
  • 测试
public class MainTest {
public static void main(String[] args) {
RedDuck redDuck = new RedDuck();
RedTurkey redTurkey = new RedTurkey();
Duck duckTurkey = new TurkeyAdapter(redTurkey);
duckTurkey.gaga();
duckTurkey.fly();
}
}


标签:fly,turkey,--,Turkey,适配器,public,Override,设计模式,void
From: https://blog.51cto.com/u_13987312/5992415

相关文章