我不会使用适配器或完整的存储库(CRUD 操作),而是使用 IReader 接口进行读取,并使用访问者模式进行插入更新删除,因此您可以将域逻辑与基础设施(持久性)细节分开,这是想法:
public class MyBusinessObject : IAcceptBusinessVisitor, IAcceptMyBusinessIdVisitor
{
private readonly string _id;
private string MyPrivateProp { get; set; }
//Fully encapsulated object
public MyBusinessObject(string id, string myPrivateProp)
{
_id = id;
MyPrivateProp = myPrivateProp;
}
public void UpdateMyProp(string newProp)
{
if (string.IsNullOrWhiteSpace(newProp)) throw new ArgumentNullException(nameof(newProp));
//Business rules ...
MyPrivateProp = newProp;
}
public void Accept(IMyBusinessObjectVisitor visitor)
{
if (visitor == null) throw new ArgumentNullException(nameof(visitor));
visitor.Visit(_id, MyPrivateProp);
}
public void Accept(IMyBusinessIdVisitor visitor)
{
if (visitor == null) throw new ArgumentNullException(nameof(visitor));
visitor.Visit(_id);
}
}
public interface IAcceptBusinessVisitor
{
void Accept(IMyBusinessObjectVisitor visitor);
}
public interface IAcceptMyBusinessIdVisitor
{
void Accept(IMyBusinessIdVisitor visitor);
}
public interface IMyBusinessObjectVisitor
{
void Visit(string id, string prop);
}
public interface IMyBusinessIdVisitor
{
void Visit(string id);
}
public class SavePersistanceVitor : IMyBusinessObjectVisitor
{
public void Visit(string id, string prop)
{
//Save to Database
}
}
public class UpdatePersistanceVitor : IMyBusinessObjectVisitor
{
public void Visit(string id, string prop)
{
//Update to Database
}
}
public class DeleteVitor : IMyBusinessIdVisitor
{
public void Visit(string id)
{
//Delete in Database
}
}
在这里阅读:
public interface IMyBusinessObjectReader
{
MyBusinessObject Read(string id);
}
class MyBusinessObjectReaderFromDb : IMyBusinessObjectReader
{
public MyBusinessObject Read(string id)
{
//Read from database
string myPrivateProp = "";
return new MyBusinessObject(id, myPrivateProp);
}
}
下一步可能是为阅读和访问者添加泛型。在这种情况下,您最终会拥有很少的小类,并获得灵活性以及单一职责、接口隔离等可靠原则的好处。因此,您可以创建一个丰富的封装域并使用一些设计原则扩展其功能。问候!