您现在的位置是:首页 >

迭代器模式菜鸟教程 C#设计模式:Adapter[1]

火烧 2022-01-20 06:06:01 1033
C#设计模式:Ada ter[1]   意图  把一个类的接口变换成客户端所期待的另一种接口 从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作   场景  假设网络游戏的客户端程序分两部分

C#设计模式:Adapter[1]  

  意图

  把一个类的接口变换成客户端所期待的另一种接口 从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作    场景

迭代器模式菜鸟教程 C#设计模式:Adapter[1]

  假设网络游戏的客户端程序分两部分 一部分是和服务端通讯的大厅部分 大厅部分提供的功能有道具购买 读取房间列表 创建房间以及启动游戏程 序 另一部分就是游戏程序了 游戏程序和大厅程序虽然属于一个客户端 但是由不同的公司在进行开发 游戏大厅通过实现约定的接口和游戏程序进行通讯

  一开始的设计就是 大厅程序是基于接口方式调用游戏程序启动游戏场景方法的 在大厅程序开发接近完成的时候 公司决定和另外一家游戏公司合作 因此希望把大厅程序能适用另一个游戏 而这个新游戏的遵循的是另一套接口 是不是可以避免修改原先调用方法来启动场景呢?或许你会说 既然只有一个方法修 改 那么修改一下也无妨 我们假设大厅程序和游戏程序之间有 个接口 其中的大部分都有修改呢?因为游戏程序接口的修改 大厅程序可能要修改不止 个地方 这样接口的意义何在呢?

  此时可以考虑使用Adapter模式来适配这种接口的不匹配情况

using System; using System Collections Generic; using System Text; namespace AdapterExample { class Program { static void Main(string[] args) { Lobby lobby = new Lobby(); lobby CreateRoom( HalfPaper ); lobby StartGame(); } } 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 ); } } class Game { public void LoadScene(string sceneName string token) { if (token == Abcd ) 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(); public void StartScene(string sceneName) { game LoadScene(sceneName Abcd ); } public void EnterPlayer(string playerName) { game EnterPlayer(GetPlayerIDByPlayerName(playerName)); } private int GetPlayerIDByPlayerName(string playerName) { return ; } } }

lishixinzhi/Article/program/net/201311/15401  
永远跟党走
  • 如果你觉得本站很棒,可以通过扫码支付打赏哦!

    • 微信收款码
    • 支付宝收款码