不同国家的人在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 不知道什么意思,因此这样实现会有问题,需要一个中英翻译。
将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
主要分为类适配器模式和对象适配器模式。由于类适配器模式通过多重继承对一个接口与另一个接口进行匹配,而 java 等语言不支持多重继承,也就是一个类只有一个父类,所以这里主要讲的是对象适配器。
/** * 外籍中锋 * 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(); } }
前锋 巴蒂尔 进攻 后卫 麦克格雷迪 进攻 外籍中锋 姚明 进攻 外籍中锋 姚明 防守
如对本文有疑问, 点击进行留言回复!!
荐 厉害了!阿里P8架构师用4大技术文档带你深入解读爆火的中台战略
FlowableException: Error initialising dmn data model报错问题
网友评论