美文网首页
学习设计模式 Day1 2020-03-30

学习设计模式 Day1 2020-03-30

作者: Taraks | 来源:发表于2020-03-30 22:38 被阅读0次

    工厂模式 Factory Pattern

    简述: 由工厂类决定实例化哪种实例,延迟创建过程,主要解决接口选择的问题。

    Step1: 实现一个interface ICar

    using System.Xml.Serialization;
    
    namespace LearnDesignPatterns.Patterns.FactoryPattern
    {
        public interface ICar
        {
            public string GetName();
        }
    }
    

    Step2: 实现ICar接口的实体类

    namespace LearnDesignPatterns.Patterns.FactoryPattern
    {
        public class BMW420i : ICar
        {
            public string Name
            {
                get => "BMW 420i";
            }
            public string GetName()
            {
                return Name;
            }
        }
        
        public class TeslaModel3 : ICar
        {
            public string Name
            {
                get => "Tesla Model III";
            }
            public string GetName()
            {
                return Name;
            }
        }
    }
    

    Step3: 创建工厂

    namespace LearnDesignPatterns.Patterns.FactoryPattern
    {
        public class CarFactory
        {
            public ICar GetCar(string carType)
            {
                return carType switch
                {
                    "BMW" => (ICar) new BMW420i(),
                    "TESLA" => new TeslaModel3(),
                    _ => null
                };
            }
        }
    }
    

    Step4: 执行&Log

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection.Metadata.Ecma335;
    
    namespace LearnDesignPatterns.Patterns.FactoryPattern
    {
        public class FactoryPatternExecutor : IExecutor
        {
            public void Execute()
            {
                var carFactory = new CarFactory();
                var cars = new List<ICar>()
                {
                    carFactory.GetCar("BMW"),
                    carFactory.GetCar("TESLA"),
                    carFactory.GetCar("TOYOTA")
                };
                foreach (var s in cars) Log(s);
            }
            private static void Log(ICar car)
            {
                Console.WriteLine(car == null
                    ? $"[Car Factory Info] This car product failed"
                    : $"[Car Factory Info] This car is {car.GetName()}");
            }
        }
    }
    

    Output:

    /usr/local/share/dotnet/dotnet /Users/garry/RiderProjects/LearnDesignPatterns/LearnDesignPatterns/bin/Debug/netcoreapp3.1/LearnDesignPatterns.dll
    [Car Factory Info] This car is BMW 420i
    [Car Factory Info] This car is Tesla Model III
    [Car Factory Info] This car product failed
    
    Process finished with exit code 0.
    

    点击查看源代码

    相关文章

      网友评论

          本文标题:学习设计模式 Day1 2020-03-30

          本文链接:https://www.haomeiwen.com/subject/wfobuhtx.html