Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the DDD Design pattern of Architecture Design

2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to analyze the DDD design pattern of architecture design, many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

1. The exposition of the problem

In the project, we are generally layered, we are most familiar with the UI,BLL,DAL layer, or add a Services service layer. This is how the general project is designed. As more and more companies and communities advocate domain-driven design (DDD), there is a hierarchical approach to projects, and some concepts in DDD design are also introduced: Presentation, Service, Domain, Repository. And in general, there are the following correspondence:

Presentation

UI

Domain

BLL

Repository

DAL

But when developing, we build a Domain class library and DAL,*** in the project: UI, Domain, DAL and so on. In fact, this is nothing, in the final analysis, it is just a matter of name, but the hidden problem behind is: do not understand DDD, most of the time only pay attention to the "shape", but do not understand the "spirit".

In the project is not the establishment of the name of Presentation, Domain, Repository class library, this project is DDD development, not like this. Originally, I am familiar with using UI,BLL,DAL in layering, but such a mix-up complicates the concept.

Moreover, in the project, whether to adopt the original simple three-tier or DDD development needs to be considered, not the DDD method. In other words, don't DDD for the sake of DDD. Just like we learned about design patterns, there is no need to design patterns for design patterns in the process of writing code.

two。 Design method

Whether to adopt DDD or the simple three layers mainly depends on the design of the business layer and the complexity of the system.

If the system is really complex and the business logic is quite complex, then DDD is recommended, because the introduction of DDD is to solve the complexity. Because the DDD method is used to design the business logic layer, then the business logic layer only pays attention to the processing of the business logic, but does not care about how to store and obtain the data, so based on this reason, the concept of Repository is introduced into the DDD. Repository is to assist the business logic layer to process the data.

Although I have been talking about "simple three layers", in fact, there is no obvious distinction between DDD and it. Here I specially divide them, mainly because we usually have three layers (or N layers) in project development. This is mainly for the convenience of discussing some problems later.

The following begins to talk about some business logic layer design methods, I believe that after you read it, a lot of doubts will be easily solved.

There are three ways to design the business layer: Transaction Script, Active Record and Domain Model.

Friends who have read Flower's book should be familiar with the above three words. In the book, these concepts are really refined, perhaps because they are refined, so it is not easy to understand.

In this article, this knowledge is involved, and only by clarifying these points, the previous problems can be solved.

If you are familiar with these concepts, you might as well take a look, and we can communicate!

First of all, let's take a look at Transaction Script (the reason why it is not translated into Chinese, because the translated Chinese meaning is easily misleading)

In fact, Transaction Script is a process of design, the most intuitive performance is a method, each method to do a business process. Let's look at the following example. The background of the example is the order processing process in an e-commerce site.

Public class OrderManager {public void PlaceOrder (OrderDTO order) {/ / Validate order based on business rules / / Check for stock availablity on items ordered / / Add the order to the database / / Set the order id on the OrderDTO object} public bool CancelOrder (Guid orderId) / Retrieve order from database / / Determine if the order can be canceled / / if order can be canceled Set as canceled / / return true/false if order was canceled} public bool AddItemToOrder (Guid orderId OrderItemDTO ItemToAdd) {/ / Retrieve order from database / / Determine if the item can be added to the order / / Add a new item row in the database / / return true/false if item was added to the order} public bool ProcessOrder (Guid orderId) {/ / Check to ensure this order can be processed. / / Validate order based on business rules / / Update the stock levels of products ordered / / return true/false if order was processed}}

In the above code, all the logic related to order processing is written in the OrderManager class. Each method in the class corresponds to a process or a use case in the business logic, for example, CancelOrder is to cancel the order.

A good advantage of organizing business logic through Transaction Script is that it is intuitive and easy to understand what the code is doing. If a new process comes, just add another method.

At the same time, the disadvantage of this organization is that when the business in the system becomes more and more complex, then such methods begin to become more and more, and the result is that there are hundreds of methods in a class. And in these methods, in addition to some basic validation can be extracted for method reuse, other process control code has to be rewritten in many places, especially when two processes are similar, the code will inevitably be rewritten. As a result, such classes begin to become large and difficult to manage.

Active Record

This kind of organization is already the most familiar to us.

In many projects, our business entity class basically corresponds to the tables in the database. For example, an Order business class represents the Order table in the database. And in the usual project, the "simple three layers (N layer)" is generally based on this way in the organization logic.

The difference in this way is that each business class is responsible for its own data access, that is, business logic processing and data access are included in the business class.

For example:

Public class Order {private Guid _ id; private DateTime _ creationDate; private int _ shippingMethod; private int _ status; private List _ orderItems; public Guid Id {get {return _ id;} set {_ id = value;}} public List OrderItems {get {return _ orderItems;} set {_ orderItems = value }} / / Business Logic public void Place () {/ / Validate order based on business rules to ensure it is in / / a good state to add to the database / / Check for stock availablity on items ordered this.Add ();} public void Cancel () {/ / Check to ensure this order can be canceled. This.Status = Status.Cancelled (); this.Save ();} public void ProcessOrder () {/ / Check to ensure this order can be processed. / / Validate order based on business rules / / Udpate the stock levels of products ordered} / / Data Access Methods public void Save () {/ / Code to persist changes to the database} public void Add () {/ / Code to Add this object to the database} public void Delete () {/ / Code to remove this object from The database} public static List FindAll () {/ / Code to retrive all Orders from the database} public static Order FindBy (Guid id) {/ / Code to retrive a specific Order from the database}}

In the above code, the Order class contains the code for business logic processing, such as Cancel, Process. The data access code is also called through these methods to save the data.

If there is an one-to-one correspondence between business classes and data tables in a development project, such as in a development blog or forum, the Active Record approach is appropriate.

I believe that many projects are based on this approach in the development and organization of logic layer, the disadvantage of this method is: as long as the database table is changed, then the business logic layer changes, and this change will spread to the UI side.

Domain Model

When organizing the business layer in this way, the business layer only focuses on transforming real-world concepts into corresponding business logic models, without paying attention to other aspects. For example, in the development of e-commerce websites, some concepts are modeled and represented as business models (that is, business classes), Order, Shopping Cart, Customer and so on. And the difference from Active Record*** is that the business classes in Domain Model do not correspond to the table one by one. The following figure is a good example:

And the most important feature is that each business class contains a lot of business verification, status tracking and so on. The responsibility is simple and easy to maintain and understand.

The sample code is as follows:

Public class Order {private Guid _ id; public Guid Id {get {return _ id;} set {_ id = value;}} public float ShippingCost () {return ShippingMethod.ShippingCostTo (this.DispatchAddress, this.ItemsTotalWeight ());} public float Total () {return DiscountOffer.TotalPriceWithDiscountOfferAppliedTo (this.Items, ShippingCost ()) } public void Process () {if (this.CanProcess ()) {/ / Charge the card Customer.Card.Charge (this.Total ()); / / Set the status of the order this.Status = Status.Shipped / / Adjust the stock levels foreach (OrderItem item in Items) {item.Product.DecreaseStockBy (item.QtyOrdered) } else {throw new InvalidOrderStateForOperationException (String.Format ("Order {0} cannot be processed in its current state {1}", this.Id, this.Status.ToString ()) }} public bool CanProcess () {if (! this.Status = = Status.Shipped & &! this.Status = Status.Cancelled) {return (this.HasEnoughStockFor (me.Items) & & GetBrokenRules.Count () = = 0);} else {return false }} public List GetBrokenRules () {List brokenRules = new List (); if (Customer = = null) brokenRules.Add (new BrokenBusinessRule () {Property = "Customer", Rule = "An Order must have a Customer"}) Else if (Customer.GetBrokenRules (). Count > 0) {AddToBrokenRulesList (brokenRules, Customer.GetBrokenRules ());} if (DispatchAddress = = null) brokenRules.Add (new BrokenBusinessRule () {Property = "DispatchAddress", Rule = "An Order must have a DispatchAddress"}) Else if (DispatchAddress.GetBrokenRules (). Count > 0) {AddToBrokenRulesList (brokenRules, DispatchAddress.GetBrokenRules ());} / /. Return brokenRules;}}

Part of the code for the Order business class, but as you can see from the code, this class contains a wealth of business logic. For example, in the Process method, the following process is handled:

1. Call the CanProcess method to verify the following:

A. whether Order is in a suitable state that can be dealt with.

b. Is there enough stock of the items ordered in Order?

2. Customer users pay for this order. As for how to pay, this logic is contained in the card class.

3. Then, update the inventory of the product.

As you can see, Domain Model is a good way to organize complex business logic, and the code is easy to read and understand (if you add refactoring).

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report