Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "static overloaded const" in C#?

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?

like image 269
Zeta Two Avatar asked Jun 02 '11 09:06

Zeta Two


3 Answers

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.

enter image description here

You have some C# samples here: http://www.dofactory.com/Patterns/PatternFlyweight.aspx#_self2

like image 121
Marino Šimić Avatar answered Oct 19 '22 23:10

Marino Šimić


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";
    }
  }
}
like image 34
Ozair Kafray Avatar answered Oct 19 '22 23:10

Ozair Kafray


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; }
  }
}
like image 1
ColinE Avatar answered Oct 20 '22 00:10

ColinE