首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 設計模式實戰:Abstract Factory 抽象工廠模式完整解析(一)

     編輯:關於C語言

模式意圖

提供一個介面,建立一系列相關或相依物件,而無需指定其具體類別。

應用場景:FPS 遊戲場景初始化

休閒 FPS 遊戲,8-16 人分組對戰。場景初始化需載入兩大元素:模型(骨架)與 紋理(貼圖)。地圖數量持續增加,若直接在代碼中硬編碼具體類別,擴充極其困難。引入 Abstract Factory,工廠產出介面/抽象類別,新增場景無需修改載入邏輯。

完整實作代碼


using System;
using System.Reflection;

namespace AbstractFactoryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Patrix patrix = new Patrix();
            patrix.LoadScene("HalfPaper");
            patrix.LoadScene("Matrix");
        }
    }

    class Patrix
    {
        private PatrixSceneFactory GetGameScene(string sceneName)
        {
            return (PatrixSceneFactory)Assembly.Load("AbstractFactoryExample")
                .CreateInstance("AbstractFactoryExample." + sceneName);
        }

        public void LoadScene(string sceneName)
        {
            PatrixSceneFactory psf = GetGameScene(sceneName);
            Texture texture = psf.CreateTexture();
            Model model = psf.CreateModel();
            model.FillTexture(texture);
        }
    }

    abstract class PatrixSceneFactory
    {
        public abstract Model CreateModel();
        public abstract Texture CreateTexture();
    }

    abstract class Model
    {
        public abstract void FillTexture(Texture texture);
    }

    abstract class Texture { }

    // HalfPaper 場景系列
    class HalfPaper : PatrixSceneFactory
    {
        public override Model CreateModel() => new HalfPaperModel();
        public override Texture CreateTexture() => new HalfPaperTexture();
    }
    class HalfPaperModel : Model
    {
        public HalfPaperModel() => Console.WriteLine("HalfPaper Model Created");
        public override void FillTexture(Texture texture) => Console.WriteLine("HalfPaper Model is filled Texture");
    }
    class HalfPaperTexture : Texture
    {
        public HalfPaperTexture() => Console.WriteLine("HalfPaper Texture Created");
    }

    // Matrix 場景系列
    class Matrix : PatrixSceneFactory
    {
        public override Model CreateModel() => new MatrixModel();
        public override Texture CreateTexture() => new MatrixTexture();
    }
    class MatrixModel : Model
    {
        public MatrixModel() => Console.WriteLine("Matrix Model Created");
        public override void FillTexture(Texture texture) => Console.WriteLine("Matrix Model is filled Texture");
    }
    class MatrixTexture : Texture
    {
        public MatrixTexture() => Console.WriteLine("Matrix Texture Created");
    }
}

角色對應表

角色類別說明
AbstractFactoryPatrixSceneFactory宣告建立系列產品的介面
ConcreteFactoryHalfPaper, Matrix實作具體產品建立邏輯
AbstractProductModel, Texture產品抽象介面
ConcreteProductHalfPaperModel, MatrixTexture 等具體產品實作
ClientPatrix透過工廠介面使用產品
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved