資料訪問層、商務邏輯層、展示層、業務實體層;
1、資料訪問層的設計:首先定義一個介面,裡面定義了對一張表或一個對象的增刪改查操作,然後定義一個類去實現上面的介面;
2、商務邏輯層:同樣先定義一個介面,裡面定義各種商務邏輯,然後定義一個類去實現上面的介面;
3、展示層:引用商務邏輯層的介面,調用其中的方法;
4、業務實體層;
改進(1)
泛型的引入:首先在設計資料訪問層時,第一個介面就定義為泛型介面
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace IData{ public interface IData<T> { IList<T> GetAll(); }}
然後每個實體類去分別實現泛型介面:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using DomainTest;using IData;using System.Data.SqlClient;namespace IDataLLimpl{ public class CustomerDataimpl:IData<Customer> { public IList<Customer> GetAll() { SqlConnection con = new SqlConnection(Connectionstring.str); SqlCommand cmd = new SqlCommand("select CustomerID,CompanyName from Customers", con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); IList<Customer> ls = new List<Customer>(); while (reader.Read()) { Customer c = new Customer(); c.CustomerId = reader[0].ToString (); c.CompanyName = reader[1].ToString (); ls.Add(c); } con.Close(); return ls; } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using IData;using DomainTest;using System.Data.SqlClient;using System.Configuration;namespace IDataLLimpl{ public class ProductDataimpl:IData<Product> { public IList<Product> GetAll() { SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["constr"]); SqlCommand cmd = new SqlCommand("select ProductId,ProductName from Products",con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); List<Product> ls = new List<Product>(); while (reader.Read()) { Product p = new Product(); p.Id = reader[0].ToString(); p.Productname = reader[1].ToString(); ls.Add(p); } con.Close(); return ls; } }}
這樣一來資料訪問層就基本實現了,如果以後需要增加業務對象,只需要直接繼承和實現泛型介面,利於擴充,下面開始商務邏輯層的設計:
這裡需要也需要一個介面,裡面定義了一些泛型方法:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using DomainTest;namespace IBLL{ public interface IBLLTest { IList<T> GetAll<T>(); }}
然後接著在另一個程式集裡引用並實現這些泛型方法;
using System;using System.Collections.Generic;using System.Linq;using System.Text;using DomainTest;using IBLL;using IData;using IDataLLimpl;namespace Bllimpl{ public class BllimplTest:IBLLTest { private IData<T> GetObj<T>( ) { if (typeof(T) == typeof(Product)) { return (IData<T>)new ProductDataimpl(); } else { return (IData<T>)new CustomerDataimpl(); } } public IList<T> GetAll<T>() { return GetObj<T>().GetAll(); } }}
用戶端調用:
protected void Page_Load(object sender, EventArgs e) { IBLLTest h = new BllimplTest(); GridView1.DataSource = h.GetAll<Customer>(); GridView1.DataBind(); }
這樣一個結構就算是基本完成了;引入泛型的好處是使得程式的擴充性更強,
執行個體下載
另外添加工廠設計模式,通過 IoC 或者 "配置反射" 來獲得具體的資料層DAL實作類別,可以減少層之間的耦合,也便於資料系統的替換(多層加IOC模式);