ddd 发表于 2023-06-15 15:17:50 字数统计 231 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788// 实体基类 public abstract class Entity { public Guid Id { get; protected set; } protected Entity() { Id = Guid.NewGuid(); } } // 值对象基类 public abstract class ValueObject<T> where T : ValueObject<T> { public override bool Equals(object obj) { var other = obj as T; if (other == null) { return false; } return EqualsCore(other); } protected abstract bool EqualsCore(T other); public override int GetHashCode() { return GetHashCodeCore(); } protected abstract int GetHashCodeCore(); } // 聚合根基类 public abstract class AggregateRoot : Entity { private List<DomainEvent> _events = new List<DomainEvent>(); protected void AddEvent(DomainEvent @event) { _events.Add(@event); } public IReadOnlyList<DomainEvent> GetEvents() { return _events.AsReadOnly(); } public void ClearEvents() { _events.Clear(); } } // 领域事件基类 public abstract class DomainEvent { } // 仓储接口 public interface IRepository<T> where T : AggregateRoot { void Add(T entity); void Remove(T entity); T GetById(Guid id); } // 仓储基类 public abstract class Repository<T> : IRepository<T> where T : AggregateRoot { protected readonly List<T> _entities = new List<T>(); public void Add(T entity) { _entities.Add(entity); } public void Remove(T entity) { _entities.Remove(entity); } public T GetById(Guid id) { return _entities.FirstOrDefault(e => e.Id == id); } }