意图
把一个类的接口变换成客户端所期待的另一种接口从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作
场景
假设网络游戏的客户端程序分两部分一部分是和服务端通讯的大厅部分大厅部分提供的功能有道具购买读取房间列表创建房间以及启动游戏程 序另一部分就是游戏程序了游戏程序和大厅程序虽然属于一个客户端但是由不同的公司在进行开发游戏大厅通过实现约定的接口和游戏程序进行通讯
一开始的设计就是大厅程序是基于接口方式调用游戏程序启动游戏场景方法的在大厅程序开发接近完成的时候公司决定和另外一家游戏公司合作 因此希望把大厅程序能适用另一个游戏而这个新游戏的遵循的是另一套接口是不是可以避免修改原先调用方法来启动场景呢?或许你会说既然只有一个方法修 改那么修改一下也无妨我们假设大厅程序和游戏程序之间有个接口其中的大部分都有修改呢?因为游戏程序接口的修改大厅程序可能要修改不止 个地方这样接口的意义何在呢?
此时可以考虑使用Adapter模式来适配这种接口的不匹配情况
using System;
using SystemCollectionsGeneric;
using SystemText;
namespace AdapterExample
{
class Program
{
static void Main(string[] args)
{
Lobby lobby = new Lobby();
lobbyCreateRoom(HalfPaper);
lobbyStartGame();
}
}
interface IGame
{
void StartScene(string sceneName);
void EnterPlayer(string playerName);
}
class Lobby
{
private string sceneName;
public void CreateRoom(string sceneName)
{
thissceneName = sceneName;
}
public void StartGame()
{
IGame game = new GameAdapter();
gameStartScene(sceneName);
gameEnterPlayer(yzhu);
}
}
class Game
{
public void LoadScene(string sceneName string token)
{
if (token == Abcd)
ConsoleWriteLine(Loading + sceneName + );
else
ConsoleWriteLine(Invalid token!);
}
public void EnterPlayer(int playerID)
{
ConsoleWriteLine(player: + playerID + entered);
}
}
class GameAdapter : IGame
{
private Game game = new Game();
public void StartScene(string sceneName)
{
gameLoadScene(sceneName Abcd);
}
public void EnterPlayer(string playerName)
{
gameEnterPlayer(GetPlayerIDByPlayerName(playerName));
}
private int GetPlayerIDByPlayerName(string playerName)
{
return ;
}
}
}
[] []