我有一个包含以下代码的 BusinessLayer 项目。域对象是 FixedBankAccount(它实现了 IBankAccount)。
存储库作为域对象的公共属性并作为接口成员。如何重构它以使存储库不再是接口成员?
域对象 (FixedBankAccount) 直接使用存储库来存储数据。这是否违反了单一责任原则?如何纠正它?
注意:存储库模式是使用 LINQ to SQL 实现的。
编辑
下面给出的代码是更好的方法吗? https://codereview.stackexchange.com/questions/13148/is-it-good-code-to-satisfy-single-responsibility-principle
代码
public interface IBankAccount
{
RepositoryLayer.IRepository<RepositoryLayer.BankAccount> AccountRepository { get; set; }
int BankAccountID { get; set; }
void FreezeAccount();
}
public class FixedBankAccount : IBankAccount
{
private RepositoryLayer.IRepository<RepositoryLayer.BankAccount> accountRepository;
public RepositoryLayer.IRepository<RepositoryLayer.BankAccount> AccountRepository
{
get
{
return accountRepository;
}
set
{
accountRepository = value;
}
}
public int BankAccountID { get; set; }
public void FreezeAccount()
{
ChangeAccountStatus();
}
private void SendEmail()
{
}
private void ChangeAccountStatus()
{
RepositoryLayer.BankAccount bankAccEntity = new RepositoryLayer.BankAccount();
bankAccEntity.BankAccountID = this.BankAccountID;
accountRepository.UpdateChangesByAttach(bankAccEntity);
bankAccEntity.Status = "Frozen";
accountRepository.SubmitChanges();
}
}
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 repositroyAccount in accountsForUser)
{
DomainObjectsForBank.IBankAccount acc = null;
acc = bankFactory.CreateAccount(repositroyAccount);
if (acc != null)
{
acc.BankAccountID = repositroyAccount.BankAccountID;
acc.accountRepository = this.accountRepository;
acc.FreezeAccount();
}
}
}
}
public interface IBankAccountFactory
{
DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount);
}
public class MySimpleBankAccountFactory : IBankAccountFactory
{
public DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount)
{
DomainObjectsForBank.IBankAccount acc = null;
if (String.Equals(repositroyAccount.AccountType, "Fixed"))
{
acc = new DomainObjectsForBank.FixedBankAccount();
}
if (String.Equals(repositroyAccount.AccountType, "Savings"))
{
acc = new DomainObjectsForBank.SavingsBankAccount();
}
return acc;
}
}
阅读: