适配器模式将一个类的接口,转化成客户期望的另一个接口,适配
器让原本接口不兼容的类可以合作无间
public interface Sheep{ public void run(); public void ho(); }
public class Wolf{ public void run(){ System.out.println("狼跑"); } public void ho(){ System.out.println("狼嚎"); } }
public class SheepAdapter implements Sheep{ private Wolf wolf; public SheepAdapter(Wolf wolf){ this.wolf = wolf; } @Override public void run(){ wolf.run(); } @Override public void ho(){ wolf.ho(); } }
测试适配器
public static void main(String[] args){ //狼 Wolf wolf = new Wolf(); //披着羊皮的狼 Sheep sheep = new SheepAdapter(wolf); sheep.run(); sheep.ho(); }
时间: 2024-11-01 17:51:14