ASP.NET 设计模式:应用程序分层与关注点分离(SoC)

时间:2022-05-29 17:13:34

应用程序分层设计

应用程序分层属于关注点分离的一种形式,可以通过命名空间、文件夹或采用单独的项目来实现。

ASP.NET 设计模式:应用程序分层与关注点分离(SoC)

下图为一个采用分层设计的项目结构

ASP.NET 设计模式:应用程序分层与关注点分离(SoC)

  • ASPPatterns.Chap3.Layered.Repository依赖于ASPPatterns.Chap3.Layered.Model
  • ASPPatterns.Chap3.Layered.Service依赖于ASPPatterns.Chap3.Layered.Repository和ASPPatterns.Chap3.Layered.Model
  • ASPPatterns.Chap3.Layered.Presentation依赖于ASPPatterns.Chap3.Layered.Service和ASPPatterns.Chap3.Layered.Model
  • ASPPatterns.Chap3.Layered.ConsoleApp依赖于ASPPatterns.Chap3.Layered.Repository、ASPPatterns.Chap3.Layered.Model、ASPPatterns.Chap3.Layered.Service和ASPPatterns.Chap3.Layered.Presentation

业务层

通过创建一个领域模型来存放所有正在建模的对象的业务有关的行为和数据。

//示例:商品折扣业务处理
namespace ASPPatterns.Chap3.Layered.Model
{
/// <summary>
/// 折扣接口
/// 通过策略模式,可以在运行时选择和改变算法(折扣)
/// </summary>
public interface IDiscountStrategy
{
decimal ApplyExtraDiscountsTo(decimal OriginalSalePrice);
} /// <summary>
/// 商品折扣策略-打88折
/// </summary>
public class TradeDiscountStrategy : IDiscountStrategy
{
public decimal ApplyExtraDiscountsTo(decimal OriginalSalePrice)
{
return OriginalSalePrice * 0.88M;
}
} /// <summary>
/// 无折扣
/// </summary>
public class NullDiscountStrategy : IDiscountStrategy
{
public decimal ApplyExtraDiscountsTo(decimal OriginalSalePrice)
{
return OriginalSalePrice;
}
} /// <summary>
/// 将折扣策略应用到商品的价格
/// </summary>
public class Price
{
private IDiscountStrategy _discountStrategy = new NullDiscountStrategy();
public decimal _rrp;
private decimal _sellingPrice; public Price(decimal rrp, decimal sellingPrice)
{
_rrp = rrp;
_sellingPrice = sellingPrice;
} public decimal RRP { get { return _rrp; } } public decimal SellingPrice
{
get { return _discountStrategy.ApplyExtraDiscountsTo(_sellingPrice); }
} public decimal Discount
{
get
{
if (RRP > SellingPrice)
return RRP - SellingPrice;
else
return 0;
}
} public decimal Savings
{
get
{
if (RRP > SellingPrice)
return 1 - (SellingPrice / RRP);
else
return 0;
}
} /// <summary>
/// 通过Set方法注入折扣策略
/// </summary>
public void SetDiscountStrategyTo(IDiscountStrategy discountStrategy)
{
_discountStrategy = discountStrategy;
}
} public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Price Price { get; set; }
} public enum CustomerType
{
Standard = 0,
Trade
} /// <summary>
/// 折扣策略的选择
/// </summary>
public static class DiscountFactory
{
public static IDiscountStrategy GetDiscountStrategy(CustomerType customerType)
{
switch (customerType)
{
case CustomerType.Trade:
return new TradeDiscountStrategy();
default:
return new NullDiscountStrategy();
}
}
} /// <summary>
/// 服务层与数据存储交互,意见所商品。使用仓储模式来实现该功能,但只是指定资源库接口,
/// 这里因为不希望model层牵涉到诸如使用什么类型的数据存储或使用什么类型的技术来查询等细节
/// </summary>
public interface IProductRepository
{
IList<Product> FindAll();
} /// <summary>
/// 服务类需要能够将给定的折扣策略应用到一组商品。
/// 通过扩展方法可以更灵活的创建一个自定义集合来实现该功能
/// </summary>
public static class ProductListExtensionMenthods
{
public static void Apply(this IList<Product> products, IDiscountStrategy discountStrategy)
{
foreach (var item in products)
{
item.Price.SetDiscountStrategyTo(discountStrategy);
}
}
} /// <summary>
/// 客户端与领域交互的服务类
/// </summary>
public class ProductService
{
private IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
} public IList<Product> GetAllProductsFor(CustomerType customerType)
{
IDiscountStrategy discountStrategy = DiscountFactory.GetDiscountStrategy(customerType);
IList<Product> products = _productRepository.FindAll();
products.Apply(discountStrategy);
return products;
}
}
}

服务层

服务层的作用就是充当应用的入口,为表示层提供了强类型视图模型。所谓视图模型就是平常界面上绑定的实体类。

namespace ASPPatterns.Chap3.Layered.Service
{
public class ProductViewModel
{
public int ProductId { get; set; }
public string Name { get; set; }
public string RRP { get; set; }
public string SellingPrice { get; set; }
public string Discount { get; set; }
public string Savings { get; set; }
} /// <summary>
/// 为了让客户端与服务层交互,使用Reuqest/Response消息模式
/// Reuqest由客户端提供,它将携带必要的参数,如本示例中的CustomerType
/// </summary>
public class ProductListRequest
{
public CustomerType CustomerType { get; set; }
} /// <summary>
/// 响应客户端请求的内容
/// </summary>
public class ProductListResponse
{
public bool Success { get; set; }
public string Message { get; set; }
public IList<ProductViewModel> Products { get; set; }
} /// <summary>
/// 将Product转换成ProductViewModel
/// </summary>
public static class ProductMapperExtensionMethods
{
public static IList<ProductViewModel> ConvertToProductListViewModel(this IList<Product> products)
{
IList<ProductViewModel> productViewModels = new List<ProductViewModel>();
foreach (var item in products)
{
productViewModels.Add(item.ConvertToProductViewModel());
}
return productViewModels;
} public static ProductViewModel ConvertToProductViewModel(this Product product)
{
ProductViewModel productViewModel = new ProductViewModel();
productViewModel.ProductId = product.Id;
//....其他赋值
return productViewModel;
}
} /// <summary>
/// ProductService与领域模型服务交互,检索商品列表,并将其转换成ProductListViewModel列表
/// </summary>
public class ProductService
{
private Model.ProductService _productService;
public ProductService(Model.ProductService productService)
{
_productService = productService;
} public ProductListResponse GetAllProductsFor(ProductListRequest productListRequest)
{
ProductListResponse productListResponse = new ProductListResponse();
try
{
IList<Product> productEntities = _productService.GetAllProductsFor(productListRequest.CustomerType);
productListResponse.Products = productEntities.ConvertToProductListViewModel();
productListResponse.Success = true;
}
catch (Exception)
{ productListResponse.Success = false;
}
return productListResponse;
}
}
}

数据访问层

主要是操作数据库数据的读写。比较常用的框架有Entity Framework、Hibernate,有时候像Dapper这种轻量级的类库更灵活。

namespace ASPPatterns.Chap3.Layered.Repository
{
public class ProductRepository : IProductRepository
{
public IList<Model.Product> FindAll()
{
//linq to sql return new List<Model.Product>();
}
}
}

表示层

为了将表示逻辑与用户界面分离,一般使用MVP(视图-模型-展示)模式。拥有表示层的好处是可以很容易的测试数据的表示以及系统之间的交互。

namespace ASPPatterns.Chap3.Layered.Presentation
{
public interface IProductListView
{
void Display(IList<ProductViewModel> products);
Model.CustomerType CustomerType { get; }
string ErrorMessage { set; }
} /// <summary>
/// 呈现器负责获取数据、处理用户事件并通过视图的接口更新视图
/// </summary>
public class ProductListPresenter
{
private IProductListView _productListView;
private Service.ProductService _productService;
public ProductListPresenter(IProductListView productListView, Service.ProductService productService)
{
_productListView = productListView;
_productService = productService;
} public void Display()
{
ProductListRequest productListRequest = new ProductListRequest();
productListRequest.CustomerType = _productListView.CustomerType;
ProductListResponse productListResponse = _productService.GetAllProductsFor(productListRequest);
if (productListResponse.Success)
{
_productListView.Display(productListResponse.Products);
}
else
{
_productListView.ErrorMessage = productListResponse.Message;
}
}
}
}

UI(用户体验)层

主要是实现数据的呈现以及与用户的交互。它不需要关注数据是如何从数据库获取的,只要负责处理用户事件并转发调用,将工作委托给表示层的Presenter。

总结

ASP.NET 设计模式:应用程序分层与关注点分离(SoC)

从上面的例子中我们可以看出程序分层设计的好处,应用程序的关注点分解到不同的层次,可以使程序更易于理解和维护。

《ASP.NET 设计模式》