ここでは、Department ( 部署 ) クラス と Employee ( 社員 ) クラスを使った簡単な例を挙げます。
部署には ID, 名前, メンバーといったフィールドがあることにします。
public sealed class Department
{
private readonly int _id;
private readonly string _name;
private readonly ReadOnlyCollection<Employee> _members;
public int Id
{
get
{
return this._id;
}
}
public string Name
{
get
{
return this._name;
}
}
public ReadOnlyCollection<Employee> Members
{
get
{
return this._members;
}
}
public Department(int id, string name, ReadOnlyCollection<Employee> members)
{
this._id = id;
this._name = name;
this._members = members;
}
}
社員には ID, 名前といったフィールドがあることにします。
public sealed class Employee
{
private readonly int _id;
private readonly string _name;
public int Id
{
get
{
return this._id;
}
}
public string Name
{
get
{
return this._name;
}
}
public Employee(int id, string name)
{
this._id = id;
this._name = name;
}
}
部署クラスの _members フィールドこそが、今回レイジーロードを行うことになるフィールドです。見ての通り、仮想プロキシによるレイジーロードでは、レイジーロードの為の特別な仕組みがドメインクラスに一切必要ありません。
DepartmentMapper は、仮想リストと仮想リストローダーを使用してレイジーロードを部署クラスに仕込みます。
IListLoader ジェネリックインターフェイスを実装した MembersLoader クラスはインナークラスとして定義してあります。この仮想リストローダーは EmployeeMapper クラス ( 今回コードは用意していませんが ) から部署メンバーを取得します。
public sealed class DepartmentMapper
{
public Department Find(int id)
{
DepartmentsDataSet.DepartmentsRow row = this.FindDataRow(id);
if (row == null)
{
return null;
}
string name = row.Name;
MembersLoader membersLoader = new MembersLoader(id);
VirtualList<Employee> membersVirtualList = new VirtualList<Employee>(membersLoader);
ReadOnlyCollection<Employee> members = new ReadOnlyCollection<Employee>(membersVirtualList);
return new Department(id, name, members);
}
private DepartmentsDataSet.DepartmentsRow FindDataRow(int id)
{
using (DepartmentsTableAdapter adapter = new DepartmentsTableAdapter())
{
DepartmentsDataSet.DepartmentsDataTable table = adapter.GetDataById(id);
if (table.Count == 0)
{
return null;
}
return table[0];
}
}
private sealed class MembersLoader : IListLoader<Employee>
{
private readonly int _id;
public MembersLoader(int id)
{
this._id = id;
}
public IList<Employee> Load()
{
return EmployeeMapper.Singleton.FindByDepartment(this._id);
}
}
}
これで、部署クラスの Members プロパティは、実際に使用されるまでロードを行いません。
トラックバックURL↓
http://csharper.blog57.fc2.com/tb.php/169-93c579ed