Design Pattern for Changing Object
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.
Inheritance comes to mind ;)
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.
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.
精彩评论