views:

55

answers:

3

Is there a Design Pattern for supporting different permutations object?

Version 1

public class myOjbect {

  public string field1 { get; set; } /* requirements: max length 20 */
  public int field2 { get; set; }
  . . .
  public decimal field20 { get; set; }
}

Version 2

public class myObject {

  public string field1 { get; set; } /* requirements: max length 40 */
  public int field2 { get; set; }
  . . .
  public double field20 { get; set; } /* changed data types */
  . . ./* 1 new properties */
  public double field21 { get; set; } 
}

of course I could just have separate objects, but thought there might be a good pattern for this sort of thing.

+2  A: 

Inheritance comes to mind ;)

Byron Whitlock
yes, my first thought is an abstract factory pattern, I just wanted to see if there were other ideas out there!
A: 

Descending a new class MyObjectV2 from MyObject would work for modifying the behavior of field1 and adding the 10 new fields;
it would not allow modifying the nature of filed200.

François
marking as answer - this is true. my question just was not a very good one.
+1  A: 

The Design Pattern would be called a Dictionary.

Just use a Dictionary and only allow keys depending on a status variable.

Example (C#):

class Foo
{
  private Dictionary<String, object> items = new Dictionary<String, object>();
  private Int32 state = 10;

  public void SetField(String field, object value)
  {
    if ((this.FieldAllowedForCurrentState(field)) && (this.IsCorrectTypeForField(field, value)))
    {
      this.items[field] = value;
    }
    else
    {
      throw new InvalidArgumentException("Invalid Key for State");
    }
  }
}

Overloading does not allow changing the type of a property and you'd end up with many differnt classes which is not very maintainable.

Anyways, i really recommend checking if you can implement your requirements without having to use an approach like this.

dbemerlin