意图
把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作。
IGame
|
GameAdapter--->Game
每次要调用的时候,就调用GameAdapter的方法,但是GameAdapter内部,其实有一个对Game的引用,调用GameAdapter的实质,就是调用Game的方法.
IGame接口就是适配器模式中的目标角色,这是客户所期待的接口。也是针对老的游戏程序所遵循的接口。
GameAdapter类是适配器角色,它是适配器模式的核心,用于把源接口转变为目标接口。在这里,我们看到,它实现目标接口。
问题:为什么不直接用Game实现IGame呢?
何时采用
l 从代码角度来说, 如果需要调用的类所遵循的接口并不符合系统的要求或者说并不是客户所期望的,那么可以考虑使用适配器。
l 从应用角度来说, 如果因为产品迁移、合作模块的变动,导致双方一致的接口产生了不一致,或者是希望在两个关联不大的类型之间建立一种关系的情况下可以考虑适配器模式。
适配器模式和Facade的区别是,前者是遵循接口的,后者可以是不遵循接口的,比较灵活。
适配器模式和Proxy的区别是,前者是为对象提供不同的接口,或者为对象提供相同接口,并且前者有一点后补的味道,后者是在设计时就会运用的。
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AdapterExample { class Program { static void Main(string[] args) { Lobby lobby = new Lobby(); lobby.CreateRoom("HalfPaper"); lobby.StartGame(); } } /// <summary> /// 游戏接口 /// </summary> interface IGame { void StartScene(string sceneName); void EnterPlayer(string playerName); } class Lobby { private string sceneName; public void CreateRoom(string sceneName) { this.sceneName = sceneName; } public void StartGame() { IGame game = new GameAdapter(); game.StartScene(sceneName); game.EnterPlayer("yzhu"); } } /// <summary> /// 目标客户端类 /// </summary> class Game { public void LoadScene(string sceneName, string token) { if (token == "Abcd1234") Console.WriteLine("Loading " + sceneName + "..."); else Console.WriteLine("Invalid token!"); } public void EnterPlayer(int playerID) { Console.WriteLine("player:" + playerID + " entered"); } } class GameAdapter : IGame { private Game game = new Game(); /// <summary> /// 实现 /// </summary> /// <param name="sceneName"></param> public void StartScene(string sceneName) { game.LoadScene(sceneName, "Abcd1234"); } /// <summary> /// 实现 /// </summary> /// <param name="playerName"></param> public void EnterPlayer(string playerName) { game.EnterPlayer(GetPlayerIDByPlayerName(playerName)); } private int GetPlayerIDByPlayerName(string playerName) { return 12345; } } }
UML源图:https://skydrive.live.com/#cid=6B286CBEF1610557&id=6B286CBEF1610557!729
代码:https://skydrive.live.com/#cid=6B286CBEF1610557&id=6B286CBEF1610557!729