领域驱动设计(Domain-Driven Design,简称DDD)是一种软件设计方法论,强调以业务领域本身为中心进行软件设计和开发。它鼓励开发者从业务专家的角度出发理解业务需求,并将这种理解反映在软件设计中。领域驱动设计包括实体(Entities)、值对象(Value Objects)、服务(Services)、聚合(Aggregates)、仓库(Repositories)等核心概念。

1、实体(Entity)

实体是具有唯一标识的对象,代码如下,

public class Post {
    public Guid Id { get; private set; } // 唯一标识
    public string Title { get; private set; } // 标题
    public string Content { get; private set; } // 内容

    public Post(Guid id, string title, string content) {
        Id = id;
        Title = title;
        Content = content;
    }

    // 业务逻辑方法
    public void UpdateContent(string content) {
        Content = content;
    }
}

2、值对象(Value Object)

值对象是没有唯一标识的不可变对象,代码如下,

public class CommentContent {
    public string Content { get; private set; }

    public CommentContent(string content) {
        Content = content;
    }
}

3、聚合/聚合根(Aggregate/Aggregate Root)

聚合是一组相关对象的集合,聚合根则是聚合内部的一个实体,它是聚合的入口。

public class BlogPost : Post { // BlogPost 作为聚合根继承自 Post
    private List<Comment> _comments = new List<Comment>();
    public IReadOnlyCollection<Comment> Comments => _comments.AsReadOnly();

    public BlogPost(Guid id, string title, string content) : base(id, title, content) {
    }

    public void AddComment(Comment comment) {
        _comments.Add(comment);
    }
}

4、领域服务(Domain Service)

领域服务包含领域逻辑,通常是一些涉及多个实体和值对象的操作。

public class PostService {
    public void PublishPost(BlogPost post) {
        // 这里可以包含发布文章的领域逻辑
    }
}

5、领域事件(Domain Event)

领域事件是领域内发生的重要业务事件。

public class PostPublishedEvent {
    public Guid PostId { get; private set; }

    public PostPublishedEvent(Guid postId) {
        PostId = postId;
    }
}

6、仓库(Repository)

仓库用于封装领域内的对象持久化逻辑。

public interface IPostRepository {
    Post GetById(Guid id);
    void Save(Post post);
}

7、应用服务(Application Service)

应用服务作为领域和用户界面之间的桥梁,处理应用逻辑。

public class BlogApplicationService {
    private readonly IPostRepository _postRepository;

    public BlogApplicationService(IPostRepository postRepository) {
        _postRepository = postRepository;
    }

    public void CreatePost(string title, string content) {
        var post = new BlogPost(Guid.NewGuid(), title, content);
        _postRepository.Save(post);
    }
}

推荐文档