假设我们有一个 Potato 类(以及因此的实例),它具有用于其他方法但不假装为 public 的属性 smoothness。此属性在创建实例时设置,并且仅在实例内部使用。
此外,我的系统应该支持多个数据库驱动程序,因此我有一个接口“数据库适配器”,它将使用使用我目前要使用的驱动程序的类进行实例化。
现在问题来了。我需要使对象(马铃薯)持久化并将其保存到数据库中,因此我应该使用数据库适配器类来保存马铃薯的平滑度,但是..它是私有的!如何发送马铃薯的光滑度而不使其可用于其他目的?
提前致谢
假设我们有一个 Potato 类(以及因此的实例),它具有用于其他方法但不假装为 public 的属性 smoothness。此属性在创建实例时设置,并且仅在实例内部使用。
此外,我的系统应该支持多个数据库驱动程序,因此我有一个接口“数据库适配器”,它将使用使用我目前要使用的驱动程序的类进行实例化。
现在问题来了。我需要使对象(马铃薯)持久化并将其保存到数据库中,因此我应该使用数据库适配器类来保存马铃薯的平滑度,但是..它是私有的!如何发送马铃薯的光滑度而不使其可用于其他目的?
提前致谢
您可以创建一个导入器/导出器接口对,将其“状态”外部化,Potato
而无需访问其实现细节(在这种情况下,它的私有成员和数据类型)。他们是建设者的类型。
public class Potato {
public interface IExporter {
void AddSmoothness(string value);
}
public interface IImporter {
string ProvideSmoothness();
}
public Potato(IImporter importer) {
this.smoothness = int.Parse(importer.ProvideSmoothness());
}
public void Export(IExporter exporter) {
exporter.AddSmoothness(this.smoothness.ToString());
}
public Potato(int smoothness) {
this.smoothness = smoothness;
}
private int smoothness;
}
然后,您的数据库适配器类将实现相关接口并使用相应的方法。在这里寻找最初的想法。
编写一个允许对象保存自己的方法,将某种编写器作为参数。由于这是一个数据库,您可能需要同时拥有 Insert 和 Update 方法,而不仅仅是 Save 方法。您也可以将它们放入接口中。
粗略的例子:
public interface IDatabaseSaveable
{
void InsertToDatabase(Database pDatabase);
void UpdateDatabase(Database pDatabase);
}
public class Potato : IDatabaseSaveable
{
private int mID;
private double mSmoothness;
public void InsertToDatabase(Database pDatabase)
{
pDatabase.InsertToPotatoes(mID, mSmoothness, ...);
}
public void UpdateDatabase(Database pDatabase)
{
pDatabase.UpdatePotatoes(mID, mSmoothness, ...);
}
}
这是将平滑度属性标记为 的变体internal
。假设土豆必须有一个smoothness
集合才能使用它,那么内部构造函数可能会更好。我会相信有一个很好的理由来隐藏平滑度。或许是马铃薯的谦虚?
public class Potato
{
internal int Smoothness { get; set; }
internal Potato(int smoothness)
{
this.Smoothness = smoothness;
}
private Potato() { }
}
只有同一程序集中的类才能Potato
使用内部构造函数实例化 a。并且只有同一个程序集中的类才能访问 Smoothness(这样他们就可以保存马铃薯了。)