适配器模式:将一个类的借口转换成客户希望的另外一个接口。
应用场景:系统的数据和行为都正确,但接口不符时,我们应该考虑使用适配器模式,目的是使控制范围之外的一个原有对象与某个接口匹配。主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
注意:应该注意其应用场景,不能本末倒置。
/** * Created by hero on 16-4-4. */ public abstract class Player { private String name; public abstract void attack(); public Player(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } /** * Created by hero on 16-4-4. */ public class Forward extends Player { @Override public void attack() { System.out.println("forward player " + getName() + " attack."); } public Forward(String name) { super(name); } } /** * Created by hero on 16-4-4. */ public class ForeignCenter { private String name; public void 进攻() { System.out.println("外籍中锋 " + name + " 进攻"); } public ForeignCenter(String name) { this.name = name; } } /** * Created by hero on 16-4-4. */ public class Translator extends Player { private ForeignCenter center; @Override public void attack() { center.进攻(); } public Translator(String name) { super(name); center = new ForeignCenter(name); } } public class Main { public static void main(String[] args) { Player hhd = new Forward("hhd"); hhd.attack(); Player ym = new Translator("ym"); ym.attack(); } }
时间: 2024-10-24 17:10:25