标签:adapter creat public 分享 ack 适配器 enc 客户 需求
将一个类的接口,转换成客户期望的另一个接口。适配器模式让原本接口不兼容的类可以合作无间。
/**
* 鸭子接口
*
* @author Colin
* @create 2018-05-07
**/
public interface Duck {
public void quack();
public void fly();
}
/**
* 鸡
*
* @author Colin
* @create 2018-05-07
**/
public interface Chicken {
public void Gege();
public void fly();
}
**
* 适配器
*
* @author Colin
* @create 2018-05-07
**/
public class ChickenAdapter implements Duck {
private Chicken chicken;
public ChickenAdapter(Chicken chicken){
this.chicken=chicken;
}
@Override
public void quack() {
chicken.Gege();
}
@Override
public void fly() {
chicken.fly();
}
}
/**
* 绿鸭子
*
* @author Colin
* @create 2018-05-07
**/
public class GreenDuck implements Duck {
@Override
public void quack() {
System.out.println("呱呱叫!");
}
@Override
public void fly() {
System.out.println("飞起来!");
}
}
/**
* 母鸡
*
* @author Colin
* @create 2018-05-07
**/
public class HenChicken implements Chicken {
@Override
public void Gege() {
System.out.println("母鸡咯咯叫!");
}
@Override
public void fly() {
System.out.println("母鸡会飞!");
}
}
public class AdapterTest {
@Test
public void testAdapter(){
GreenDuck greenDuck=new GreenDuck();
HenChicken chicken=new HenChicken();
Duck duck=new ChickenAdapter(chicken);
duck.quack();
duck.fly();
}
}
标签:adapter creat public 分享 ack 适配器 enc 客户 需求
原文地址:https://www.cnblogs.com/coliz/p/9021731.html