w00*_*977 2 c# domain-driven-design
在谈论六角形架构时,我试图理解端口和适配器的含义。今晚我读了很多解释,但是我还没有找到代码示例。因此我将设计一个。我将端口理解为一个接口。例如:
public interface IPerson
{
string GetName();
}
Run Code Online (Sandbox Code Playgroud)
适配器是实现接口的类:
public class Person : IPerson
{
//Implementation of GetName here
}
Run Code Online (Sandbox Code Playgroud)
我理解四联适配器模式的概念。但是,我不明白这如何适合 DDD。
在 DDD 上下文中查看一个简单的代码示例确实对我有帮助。
适配器是实现接口的类
不总是。对于从动端来说确实如此,但对于驱动程序端来说,适配器是使用接口(调用其方法)的软件组件。
我写了一篇关于端口和适配器模式(六边形架构)的概念性文章:
https://softwarecampament.wordpress.com/portsadapters
您可以在那里阅读相关内容。
今晚我读了很多解释,但是我还没有找到代码示例。
我刚刚发明的一些代码,向您解释什么是端口和适配器在实践中:
在在线商店中,驱动程序端口可以是:
public interface ForManagingShoppingCart {
public void addProductToShoppingCart ( String productId );
// ... more methods ...
}
Run Code Online (Sandbox Code Playgroud)
驱动程序适配器可以是一个控制器,它从 UI 接收用户请求并调用驱动程序端口的方法:
public class ShoppingCartController {
private final ForManagingShoppingCart forManagingShoppingCart;
// Injects port in the constructor
public ShoppingCartController ( ForManagingShoppingCart forManagingShoppingCart ) {
this.forManagingShoppingCart = forManagingShoppingCart;
}
// Method that executes when user selects a product in the view and clicks the "add product" button
public void addProductOnClick ( String productId ) {
this.forManagingShoppingCart.addProductToShoppingCart ( productId );
}
}
Run Code Online (Sandbox Code Playgroud)
如果应用程序在您执行采购订单时向您发送电子邮件,则驱动端口可能是:
public interface ForNotifyingClients {
public void sendPurchaseOrderConfirmation ( String recipient );
}
Run Code Online (Sandbox Code Playgroud)
该端口与技术无关,它不知道消息是否通过电子邮件发送。驱动适配器使用电子邮件系统实现端口。
我理解四联适配器模式的概念。
适配器模式很适合,因为您要将端口接口方法转换为电子邮件系统接口方法。
public class EmailNotificationAdapter implements ForNotifyingClients {
private final EmailSystem emailSystem;
// Inject the email system interface you want to use in the adapter constructor
public EmailNotificationAdapter ( EmailSystem emailSystem ) {
this.emailSystem = emailSystem;
}
// Implements the method using the email system to send an email
@Override
public void sendPurchaseOrderConfirmation ( String recipient ) {
// ...code that sends an email to the recipient using this.emailSystem
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白这如何适合 DDD...在 DDD 上下文中查看一个简单的代码示例确实对我有帮助。
DDD 非常适合六边形架构:
| 归档时间: |
|
| 查看次数: |
2820 次 |
| 最近记录: |