資源描述:
《設(shè)計(jì)模式3:abstract factory(抽象工廠)》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、無廢話C#設(shè)計(jì)模式之三:AbstractFactory意圖提供一個(gè)創(chuàng)建一系列相關(guān)或相互依賴對(duì)象的接口,而無需指定它們具體的類。場景還是上次說的那個(gè)網(wǎng)絡(luò)游戲,定下來是一個(gè)休閑的FPS游戲。和CS差不多,8到16個(gè)玩家在游戲里面分成2組對(duì)戰(zhàn)射擊?,F(xiàn)在要實(shí)現(xiàn)初始化場景的工作。要呈現(xiàn)一個(gè)三維物體一般兩個(gè)元素是少不了的,一是這個(gè)物體的骨架,也就是模型,二就是這個(gè)骨架上填充的紋理。我們知道,這樣的一個(gè)游戲不可能只有一張地圖,而且地圖的數(shù)量肯定是會(huì)一直增加的。如果游戲在初始化場景的時(shí)候需要根據(jù)不同的地圖分別加載模型和紋理對(duì)象,那么勢必
2、就會(huì)使得場景的擴(kuò)充變得很不方便。由此,我們引入AbstractFactory,抽象工廠生產(chǎn)的都是實(shí)際類型的接口(或者抽象類型),如果加了新的場景可以確保不需要修改加載場景的那部分代碼。示例代碼usingSystem;usingSystem.Reflection;namespaceAbstractFactoryExample{classProgram{staticvoidMain(string[]args){Patrixpatrix=newPatrix();patrix.LoadScene("HalfPaper");pat
3、rix.LoadScene("Matrix");}}classPatrix{privatePatrixSceneFactoryGetGameScene(stringgameSceneName){return(PatrixSceneFactory)Assembly.Load("AbstractFactoryExample").CreateInstance("AbstractFactoryExample."+gameSceneName);}publicvoidLoadScene(stringgameSceneName){Pa
4、trixSceneFactorypsf=GetGameScene(gameSceneName);Texturetexture=psf.CreateTexture();Modelmodel=psf.CreateModel();model.FillTexture(texture);}}abstractclassPatrixSceneFactory{publicabstractModelCreateModel();publicabstractTextureCreateTexture();}abstractclassModel{
5、publicabstractvoidFillTexture(Texturetexture);}abstractclassTexture{}classHalfPaper:PatrixSceneFactory{publicoverrideModelCreateModel(){returnnewHalfPaperModel();}publicoverrideTextureCreateTexture(){returnnewHalfPaperTexture();}}classHalfPaperModel:Model{publicH
6、alfPaperModel(){Console.WriteLine("HalfPaperModelCreated");}publicoverridevoidFillTexture(Texturetexture){Console.WriteLine("HalfPaperModelisfilledTexture");}}classHalfPaperTexture:Texture{publicHalfPaperTexture(){Console.WriteLine("HalfPaperTextureCreated");}}cl
7、assMatrix:PatrixSceneFactory{publicoverrideModelCreateModel(){returnnewMatrixModel();}publicoverrideTextureCreateTexture(){returnnewMatrixTexture();}}classMatrixModel:Model{publicMatrixModel(){Console.WriteLine("MatrixModelCreated");}publicoverridevoidFillTexture
8、(Texturetexture){Console.WriteLine("MatrixModelisfilledTexture");}}classMatrixTexture:Texture{publicMatrixTexture(){Console.WriteLine("MatrixTextureCreated");}