首先介绍一下备忘录模式。
定义:在不破坏封装性的前提下,捕获一个对象内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存在状态。
类图:
实现:
public class Person
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
//恢复
public void Restore(StoreBox stroeBox)
{
Name = stroeBox.Name;
Sex = stroeBox.Sex;
Age = stroeBox.Age;
}
//存档
public StoreBox Recover()
{
return new StoreBox(Name, Sex, Age);
}
}
public class StoreBox
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public StoreBox(string name, string sex, int age)
{
Name = name;
Sex = sex;
Age = age;
}
}
public class Manager
{
public StoreBox StoreBox { get; set; }
public Manager(StoreBox storeBox)
{
StoreBox = storeBox;
}
}
这是标准的备忘录模式。现在需求做一下修改,人员属性增加(体重,身高),这样就需要修改2个地方,如果只修改了Person,存档的时候就不会保存这2个属性。现在单独把Person的属性独立出来生成一个类,修改如下:
public class PersonProperty
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
public class Person
{
public PersonProperty PersonProperty { get; set; }
//恢复
public void Restore(StoreBox stroeBox)
{
PersonProperty = stroeBox.PersonProperty;
}
//存档
public StoreBox Recover()
{
return new StoreBox(PersonProperty);
}
}
public class StoreBox
{
public PersonProperty PersonProperty { get; set; }
public StoreBox(PersonProperty personProperty)
{
PersonProperty = personProperty;
}
}
public class Manager
{
public StoreBox StoreBox { get; set; }
public Manager(StoreBox storeBox)
{
StoreBox = storeBox;
}
}
现在需求再次改变,我需要对汽车的属性也做存档,这里我该怎么办呢?是新建一个存档箱么?这里我们用到泛型。使得存档箱可以存档不同对象的属性,最终代码:
public class PersonProperty
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
public class Person
{
public PersonProperty PersonPro { get; set; }
//恢复
public void Restore(StoreBox<PersonProperty> stroeBox)
{
PersonPro = stroeBox.Property;
}
//存档
public StoreBox<PersonProperty> Recover()
{
return new StoreBox<PersonProperty>(PersonPro);
}
}
public class CarProperty
{
public string Brand { get; set; }
public string Color { get; set; }
public decimal Price { get; set; }
}
public class Car
{
public CarProperty CarPro { get; set; }
//恢复
public void Restore(StoreBox<CarProperty> stroeBox)
{
CarPro = stroeBox.Property;
}
//存档
public StoreBox<CarProperty> Recover()
{
return new StoreBox<CarProperty>(CarPro);
}
}
public class StoreBox<T>
{
public T Property { get; set; }
public StoreBox(T property)
{
Property = property;
}
}
public class PersonManager
{
public StoreBox<PersonProperty> StoreBox { get; set; }
public PersonManager(StoreBox<PersonProperty> storeBox)
{
StoreBox = storeBox;
}
}
public class CarManager
{
public StoreBox<CarProperty> StoreBox { get; set; }
public CarManager(StoreBox<CarProperty> storeBox)
{
StoreBox = storeBox;
}
}