.NET MVC学习随笔

MVC虚拟数据实现:

1、新建实体类 如下:

namespace MVCDemo.Models.Entities
{
/// <summary>
/// 分类实体类
/// </summary>
public class CategoryInfo
{
public int ID { get; set; }
public string Name { get; set; }
}
}

2、在定义接口 如下:

using MVCDemo.Models.Entities;

namespace MVCDemo.Models.Interfaces
{
/// <summary>
/// 分类服务组件接口
/// </summary>
public interface ICategoryService
{
/// <summary>
/// 添加分类
/// </summary>
/// <param name="category"></param>
void Add(CategoryInfo category);

/// <summary>
/// 修改分类名称
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
void ChangeName(int id,string name);

/// <summary>
/// 删除分类
/// </summary>
/// <param name="id"></param>
void Remove(int id);

/// <summary>
/// 取得某个分类详细信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
CategoryInfo GetDetail(int id);

/// <summary>
/// 取得所有分类
/// </summary>
/// <returns></returns>
List<CategoryInfo> GetAll();
}
}

3、然后,建立两个业务逻辑服务模型。注意它们要各自实现自己的接口。

using MVCDemo.Models.Interfaces;
using MVCDemo.Models.Entities;

namespace MVCDemo.Models.MockModels
{
/// <summary>
/// “欺骗”服务组件,用于模拟分类的业务服务
/// </summary>
public class MockCategoryService : ICategoryService
{
/// <summary>
/// 添加分类
/// </summary>
/// <param name="category"></param>
public void Add(CategoryInfo category)
{
return;
}

/// <summary>
/// 修改分类名称
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
public void ChangeName(int id, string name)
{
return;
}

/// <summary>
/// 删除分类
/// </summary>
/// <param name="id"></param>
public void Remove(int id)
{
return;
}

/// <summary>
/// 取得某个分类详细信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public CategoryInfo GetDetail(int id)
{
return new CategoryInfo
{
ID = id,
Name = "最新通告",
};
}

/// <summary>
/// 取得所有分类
/// </summary>
/// <returns></returns>
public List<CategoryInfo> GetAll()
{
List<CategoryInfo> categories = new List<CategoryInfo>();
for (int i = 1; i <= 5; i++)
{
CategoryInfo category = new CategoryInfo
{
ID = i,
Name="通告类别"+i,
};

categories.Add(category);
}

return categories;
}
}
}

4、最后,我们要建立一个生成业务逻辑模型的生成器,用来实现表示层和业务逻辑层的解耦。当然,为了简化复杂度,这里没有使用依赖注入机制。

using MVCDemo.Models.Interfaces;
using MVCDemo.Models.MockModels;

namespace MVCDemo.Models
{
/// <summary>
/// 服务组件生成类,用于生成业务服务组件
/// </summary>
public sealed class ServiceBuilder
{
/// <summary>
/// 创建分类服务组件
/// </summary>
/// <returns>分类服务组件</returns>
public static ICategoryService BuildCategoryService()
{
return new MockCategoryService();
}

/// <summary>
/// 创建公告服务组件
/// </summary>
/// <returns>公告服务组件</returns>
public static IAnnounceService BuildAnnounceService()
{
return new MockAnnounceService();
}
}
}

posted @ 2012-06-24 08:54  流年莫逝  阅读(142)  评论(0编辑  收藏  举报