I'm creating a game in C#. Each level is made up of several tiles. Each tile is of a certain type e.g. grass floor, wooden wall, etc.
Ideally I would like to have one base class "Tile" and inherit from it to create classes for each type of tile. I would like to have the properties of the tile some kind of static/const/etc member of the sub-class since each type of tile is only ever going to have the same properties. I.e. I don't want 100 Tiles have a property which all have the same value, that seems rather inefficient.
The problem is you can't do that in C#. Are there any ways to achieve what I want?
My alternative idea was to separate it all into to trees, one with only the class "Tile" which represents an instance and another "TileType" from which I instanciate one object for each type and maybe access them through some kind of "TileTypeCollection". This feels strange though and I would rather do it in the first way.
Are there any general guidelines when dealing with a situation like this?
You are looking for the FlyWeight design pattern:
http://en.wikipedia.org/wiki/Flyweight_pattern
Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
You have some C# samples here: http://www.dofactory.com/Patterns/PatternFlyweight.aspx#_self2
You can create a class structure as follows:
public abstract class Tile
{
public abstract string BaseType;
}
public class Floor : Tile
{
public override string BaseType
{
get
{
return "floor";
}
}
}
public class Grass : Tile
{
public override string BaseType
{
get
{
return "grass";
}
}
}
public class Wooden : Tile
{
public override string BaseType
{
get
{
return "wooden";
}
}
}
Can't you just use a static field to back a property on your Tile base class?
public abstract class Tile
{
private static string _commonProperty
public static string CommonProperty
{
get { return _commonProperty; }
set { _commonProperty = value; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With