不一样国家的人在NBA打球,但都是用英文交流。编程
/** * 球员 * Created by callmeDevil on 2019/8/4. */ public abstract class Player { protected String name; public Player(String name){ this.name = name; } // 发起进攻 public abstract void attack(); // 转回防守 public abstract void defense(); }
/** * 前锋 * Created by callmeDevil on 2019/8/4. */ public class Forwards extends Player { public Forwards(String name){ super(name); } @Override public void attack() { System.out.println(String.format("前锋 %s 进攻", name)); } @Override public void defense() { System.out.println(String.format("前锋 %s 防守", name)); } }
/** * 中锋 * Created by callmeDevil on 2019/8/4. */ public class Center extends Player { // 代码与前锋类似 }
/** * 后卫 * Created by callmeDevil on 2019/8/4. */ public class Guards extends Player { // 代码与前锋类似 }
public class Test { public static void main(String[] args) { Player b = new Forwards("巴蒂尔"); b.attack(); Player m = new Guards("麦克格雷迪"); m.attack(); Player ym = new Center("姚明"); // 姚明问:attack 和 defense 是什么意思? ym.attack(); ym.defense(); } }
前锋 巴蒂尔 进攻 后卫 麦克格雷迪 进攻 中锋 姚明 进攻 中锋 姚明 防守
姚明刚到NBA时可能英文还不太好,也就是说听不懂教练的战术安排,attach 和 defense 不知道什么意思,所以这样实现会有问题,须要一个中英翻译。ide
将一个类的接口转换成客户但愿的另一个接口。适配器模式使得本来因为接口不兼容而不能一块儿工做的那些类能够一块儿工做。测试
主要分为类适配器模式和对象适配器模式。因为类适配器模式经过多重继承对一个接口与另外一个接口进行匹配,而 Java 等语言不支持多重继承,也就是一个类只有一个父类,因此这里主要讲的是对象适配器。this
/** * 外籍中锋 * Created by callmeDevil on 2019/8/4. */ public class ForeignCenter { // 外籍中锋球员的姓名故意用属性而不是构造方法来区别与三个球员的不一样 private String name; // 代表外籍中锋只懂中文“进攻”(注意:举例效果,实际上千万别用这种方式编程) public void 进攻(){ System.out.println(String.format("外籍中锋 %s 进攻", name)); } // 代表外籍中锋只懂中文“防守”(注意:举例效果,实际上千万别用这种方式编程) public void 防守(){ System.out.println(String.format("外籍中锋 %s 防守", name)); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
/** * 翻译者 * Created by callmeDevil on 2019/8/4. */ public class Translator extends Player{ // 声明并实例化一个内部“外籍中锋”对象,代表翻译者与外籍球员有关联 private ForeignCenter wjzf = new ForeignCenter(); public Translator(String name){ super(name); wjzf.setName(name); } @Override public void attack() { // 翻译者将“attack”翻译为“进攻”告诉外籍中锋 wjzf.进攻(); } @Override public void defense() { // 翻译者将“defense”翻译为“防守”告诉外籍中锋 wjzf.防守(); } }
public class Test { public static void main(String[] args) { Player b = new Forwards("巴蒂尔"); b.attack(); Player m = new Guards("麦克格雷迪"); m.attack(); Player ym = new Translator("姚明"); // 翻译者告诉姚明,教练要求你既要“进攻”又要“防守” ym.attack(); ym.defense(); } }
前锋 巴蒂尔 进攻 后卫 麦克格雷迪 进攻 外籍中锋 姚明 进攻 外籍中锋 姚明 防守