我正在尝试实现各种相关类组,有点像这样:
- MySQL数据库
- MySQLTable(引用一个 MySQLDatabase)
- MySQLRecord(引用 MySQLTable)
- PostGre 数据库
- PostGreTable(引用 PostGreDatabase)
- PostGreRecord(引用 PostGreTable)
- 甲骨文数据库
- ...
由于相关类(MySQLTable、PostGreTable 等)有很多共享代码,我已经使用抽象父类和泛型实现了这一点,如下所示:
class Database {}
class Table<DatabaseType> where DatabaseType : Database
{
public DatabaseType FDatabase; //this is what I mean by "references"
}
class Record<TableType, DatabaseType> where
DatabaseType : Database
TableType : Table<DatabaseType>
{
public TableType FTable;
}
class MySQLDatabase : Database {}
class MySQLTable : Table<MySQLDatabase>
{
public string FCharset;
}
MySQLRecord : Record<MySQLTable, MySQLDatabase> {}
...
我需要这种架构能够:
- 防止错误的引用。
例如:MySQLTable 不能引用 PostGreDatabase 或 OracleDatabase,只能引用 MySQLDatabase。
- 使程序员无需强制转换即可访问对象的特定属性。
例子:
SomeMySQLRecord.FTable.FCharset = 'UTF-8';
代替
((MySQLTable)SomeMySQLRecord.FTable).Charset = 'UTF-8';
我正在寻找一种更优雅的方式(或模式)来做到这一点,因为真正的类组有 3 个以上的类,而泛型真的让代码变得很糟糕。例子:
MyType : Type1<GType1, GType2, GType3, GType4> where
GType1 : Type2,
GType2 : Type3<GType1>,
GType3 : Type4<GType1, GType2>,
GType4 : Type5<GType2, GType1, Type2, GType3>