.NET 2.0 引入 Profile 提供個性化服務。本文深度剖析 PetShop 4.0 中 Profile 屬性管理的工廠模式架構、多提供者實現與配置應用。
PetShop.IProfileDAL // 接口定義 PetShop.OracleProfileDAL // Oracle 實現 PetShop.SQLProfileDAL // SQL Server 實現 PetShop.ProfileDALFactory // 工廠創建 PetShop.Profile // 高層封裝,繼承 ProfileProvider
定義 IPetShopProfileProvider 十大方法:
GetAccountInfo、SetAccountInfoGetCartItems、SetCartItemsUpdateActivityDatesGetUniqueIDCreateProfileForUser、GetInactiveProfiles、DeleteProfile、GetProfileInfoPetShop.OracleProfileDAL.PetShopProfileProvider:Oracle 實現PetShop.SQLProfileDAL.PetShopProfileProvider:SQL Server 實現public sealed class DataAccess
{
public static IPetShopProfileProvider CreatePetShopProfileProvider()
{
// 根據 web.config [ProfileDAL] 設置實例化對應提供者
}
}
典型工廠模式:配置驅動、運行時綁定具體實現。
PetShop.Profile.PetShopProfileProvider 繼承 System.Web.Profile.ProfileProvider,重寫核心方法:
InitializeGetPropertyValues、SetPropertyValuesDeleteProfiles、DeleteInactiveProfiles、FindProfilesByUserName、GetAllProfiles 等<profile automaticSaveEnabled="false" defaultProvider="ShoppingCartProvider">
<providers>
<add name="ShoppingCartProvider"
connectionStringName="SQLProfileConnString"
type="PetShop.Profile.PetShopProfileProvider"
applicationName=".NET Pet Shop 4.0"/>
<add name="WishListProvider" ... />
<add name="AccountInfoProvider" ... />
</providers>
<properties>
<add name="ShoppingCart" type="PetShop.BLL.Cart" allowAnonymous="true" provider="ShoppingCartProvider"/>
<add name="WishList" type="PetShop.BLL.Cart" allowAnonymous="true" provider="WishListProvider"/>
<add name="AccountInfo" type="PetShop.Model.AddressInfo" allowAnonymous="false" provider="AccountInfoProvider"/>
</properties>
</profile>
automaticSaveEnabled="false":手動調用 Profile.Save() 持久化allowAnonymous:匿名用戶是否可用(購物車/願望清單允許,賬戶信息需登錄)type:序列化目標類型(BLL.Cart、Model.AddressInfo)// 保存賬戶地址信息
Profile.AccountInfo = AddressForm.Address;
Profile.Save();
// 匿名遷移:Global.asax
void Profile_MigrateAnonymous(object sender, ProfileMigrateEventArgs e)
{
// 匿名用戶註冊登錄後,原匿名 Profile 數據遷移到新用戶
}
| 層次 | 職責 | 設計模式 |
|---|---|---|
| IProfileDAL | 契約定義 | 介面隔離 |
| SQL/Oracle DAL | 具體數據訪問 | 策略模式、依賴倒置 |
| ProfileDALFactory | 實例創建 | 工廠模式、配置驅動 |
| Profile | ASP.NET 整合封裝 | 適配器模式、門面模式 |