我有一个 BankAccount 表。LINQ to SQL 生成一个名为“BankAccount”的类,如下所示。
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.BankAccount")]
public partial class BankAccount : INotifyPropertyChanging, INotifyPropertyChanged
现在,作为一个新手,我自己新创建了域对象。请参阅 IBankAccount 接口和 FixedBankAccount 类。关键是存在多态行为——IBankAccount 可以是 FixedBankAccount 或 SavingsBankAccount。
对于此示例的另一个问题,我有以下两条评论。
- @mouters:“你有存储库对象和域对象很奇怪——你的存储库不应该只返回域对象吗?”</li>
- @SonOfPirate:“存储库应该使用工厂来根据从数据存储中检索到的数据创建实例。”</li>
问题
1)我手动创建域实体。这是错误的方法吗?如果错了,LINQ to SQL 类如何处理多态性?如何将方法添加到这些类?
2)存储库应该如何使用工厂来根据从数据存储中检索到的数据创建实例?任何代码示例或参考?
3) 是否满足单一职责原则?
代码
public interface IBankAccount
{
int BankAccountID { get; set; }
double Balance { get; set; }
string AccountStatus { get; set; }
void FreezeAccount();
void AddInterest();
}
public class FixedBankAccount : IBankAccount
{
public int BankAccountID { get; set; }
public string AccountStatus { get; set; }
public double Balance { get; set; }
public void FreezeAccount()
{
AccountStatus = "Frozen";
}
}
public class BankAccountService
{
RepositoryLayer.IRepository<RepositoryLayer.BankAccount> accountRepository;
ApplicationServiceForBank.IBankAccountFactory bankFactory;
public BankAccountService(RepositoryLayer.IRepository<RepositoryLayer.BankAccount> repo, IBankAccountFactory bankFact)
{
accountRepository = repo;
bankFactory = bankFact;
}
public void FreezeAllAccountsForUser(int userId)
{
IEnumerable<RepositoryLayer.BankAccount> accountsForUser = accountRepository.FindAll(p => p.BankUser.UserID == userId);
foreach (RepositoryLayer.BankAccount oneOfRepositoryAccounts in accountsForUser)
{
DomainObjectsForBank.IBankAccount domainBankAccountObj = bankFactory.CreateAccount(oneOfRepositoryAccounts);
if (domainBankAccountObj != null)
{
domainBankAccountObj.BankAccountID = oneOfRepositoryAccounts.BankAccountID;
domainBankAccountObj.FreezeAccount();
this.accountRepository.UpdateChangesByAttach(oneOfRepositoryAccounts);
oneOfRepositoryAccounts.Status = domainBankAccountObj.AccountStatus;
this.accountRepository.SubmitChanges();
}
}
}
}
public interface IBankAccountFactory
{
DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositoryAccount);
}
public class MySimpleBankAccountFactory : IBankAccountFactory
{
//Is it correct to accept repositry inside factory?
public DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositoryAccount)
{
DomainObjectsForBank.IBankAccount acc = null;
if (String.Equals(repositoryAccount.AccountType, "Fixed"))
{
acc = new DomainObjectsForBank.FixedBankAccount();
}
if (String.Equals(repositoryAccount.AccountType, "Savings"))
{
//acc = new DomainObjectsForBank.SavingsBankAccount();
}
return acc;
}
}
阅读: