[Design-Pattern] Abstract Factory Pattern

抽象工廠 - Abstract Factory

目的 : 用一個工廠介面來生產一系列相關的產物,但實際建立那些物件由實作工廠的子類別來實現

建立抽象工廠(抽象類別)

    public enum CarColor
    {
        White,
        Black,
        Blue,
        Gray
    }

    public enum CarType
    {
        Sedan,
        Coupe,
        Wagon,
        Suv,
        Convertible,
        HatchBack,
        Limousine,
        Van
    }

public abstract class Car
    {
        private CarColor _carColor;
        private CarType _carType;

        public abstract void Display();
        public abstract void SetCarColor(CarColor color);
        public abstract void SetCarType(CarType type);

        public CarColor Color {
            get => this._carColor;
            set => this._carColor = value;
        }

        public CarType CTYPE
        {
            set => this._carType = value;
            get => this._carType;
        }
    }

實作抽象工廠

public class Honda : Car
    {
        private static string Vendor = "Honda";
        public Honda()
        {
        }

        public override void Display()
        {
            Console.WriteLine($"Vendor : {Vendor}, Color : {Color}, Type : {CTYPE}");
        }

        public override void SetCarColor(CarColor color)
        {
            Color = color;
        }

        public override void SetCarType(CarType type)
        {
            CTYPE = type;
        }
    }

建立抽象工廠介面

    public interface ICarEquipFactory
    {
        CarColor ProduceCarColor();
        CarType ProduceCarType();
    }

實作抽象工廠介面

    public class HondaEquipFactory : ICarEquipFactory
    {
        public CarColor ProduceCarColor()
        {
            return CarColor.Blue;
        }

        public CarType ProduceCarType()
        {
            return CarType.Limousine;
        }
    }

建立工廠模式

    public interface ICarModel
    {
        Car MadeCar();
    }

實作工廠模式

    public class HondaCarModel : ICarModel
    {
        private static readonly ICarEquipFactory EquipFactory = new HondaEquipFactory();
        public Car MadeCar()
        {
            var honda = new Honda();
            honda.SetCarColor(EquipFactory.ProduceCarColor());
            honda.SetCarType(EquipFactory.ProduceCarType());
            return honda;
        }
    }

測試

            ICarModel hondaModel = new HondaCarModel();
            var honda = hondaModel.MadeCar();
            honda.Display();

留言

這個網誌中的熱門文章

[Tools] GCOV & LCOV 初探

Quilt Patch 管理操作方法

[C#]C# Coding 規則