Skip to content

Instantly share code, notes, and snippets.

@dasjestyr
Created July 29, 2013 20:10
Show Gist options
  • Save dasjestyr/6107345 to your computer and use it in GitHub Desktop.
Save dasjestyr/6107345 to your computer and use it in GitHub Desktop.
Adapter pattern example
class Program
{
static void Main(string[] args)
{
const string messageFormat = "{0} gave you a {1}, which is a type of {2}";
// this operation expects to use a Character object
Character _char;
_char = new Character("Cecil");
var item = _char.GetItem("Masamune");
Console.WriteLine(messageFormat, _char.Name, item.Name, item.Class);
// but what if the object was of type Npc?
var npc = new Npc("Town Fence");
_char = new NpcAdapter(npc);
item = _char.GetItem("Hammer");
Console.WriteLine(messageFormat, _char.Name, item.Name, item.Class);
}
// this will adapt the Npc object to work as if it were a Character object
public class NpcAdapter : Character
{
private readonly Npc _npc;
public NpcAdapter(Npc npc) : base(npc.Id)
{
_npc = npc;
Name = npc.Id;
}
public override Item GetItem(string itemName)
{
return _npc.Items[itemName];
}
}
public class Character
{
public string Name { get; set; }
public List<Item> Backpack { get; set; }
public Character(string name)
{
Name = name;
// make some items
Backpack = new List<Item>
{
new Item {Name = "Masamune", Class = "Sword"},
new Item {Name = "Desert Eagle", Class = "Gun"}
};
}
public virtual Item GetItem(string itemName)
{
return Backpack.Single(i => i.Name == itemName);
}
}
public class Npc
{
public string Id { get; set; }
public Dictionary<string, Item> Items { get; set; }
public Npc(string id)
{
Id = id;
// make some items
Items = new Dictionary<string, Item>();
Items.Add("Brie", new Item { Name = "Brie", Class = "Food"});
Items.Add("Hammer", new Item { Name = "Hammer", Class = "Tool" });
}
}
public class Item
{
public string Name { get; set; }
public string Class { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment