我试图实现一些相关类的分组,类似于这样:
- MySQLDatabase
- MySQLTable(引用MySQLDatabase)
- MySQLRecord(引用MySQLTable)
- PostGreDatabase
- PostGreTable(引用PostGreDatabase)
- PostGreRecord(引用PostGreTable)
- OracleDatabase
- ...
由于相关类(如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>