Trying to separate code in a client server model where the client isn't trusted and with minimal duplication
I am working on a client/server game (C#.NET) where I do not want to trust the client to hold any of my server side application code, but want to share objects.
For example imagine you have a right hand weapon s开发者_StackOverflow社区lot and a backpack that can carry additional items. Now there's a lot of server side code that will control which items can go in which slots and when you swing your right hand what happens. I don't want to put this code in my client for various reasons, but I am finding often times that if I generate a client side class and server side class for each of these that I see a lot of duplication in data and some duplication in methods. I also have to convert 1 class into the other.
Another example is For Items in the game. Item's have 'Use' abilities (like Use a key, or Use a torch) and properties like Name and Weight. So When I create the Item Class I would prefer to make 1 class like this:
Public Class Item
{
int Weight;
string Name;
void Use() { //Do something interesting but not public to the client }
}
Eventually copies of this object are serialized and sent to the client or server from each other as changes are made. If a Partial Class could span projects that would be very promising (to bad they don't). I don't think sub-classing feels right here (like ServerItem : Item
) considering Serialization/Deserialization. I will play around some with Extension methods and see what implications there are for sub-classing but if anyone has any ideas or if I'm just missing something obvious please let me know.
You really want to separate Data from Behaviour, and have just lightweight share-able data classes, and then (on the server) have server-centric classes that use data to determine behaviour. (try looking at a few design patters - maybe 'Decorator')
One lightweight example of what you may want is:
// lightweight data class thats shared
public class Item
{
public int Weight { get; set; }
public string Name { get; set; }
}
// decorator pattern class that adds behaviour
public class ServerItem
{
private Item item;
public ServerItem(Item item)
{
this.item = item;
}
public void Use()
{
// do something with item;
}
}
ServerItem currentServerItem = new ServerItem(currentItem);
精彩评论