首页 > 解决方案 > 工厂模式中使用的策略模式?

问题描述

我正在使用工厂模式编写代码。在 switch 情况下,我实际上是在返回 Class 对象。使用这个返回类,我将调用一个方法。这是策略模式的一个例子吗?

using System;
using System.Linq;

namespace ConsoleApplication1
{
    public interface IVehicle
    {
          void Manufacture();
    }

    public class Car : IVehicle
    {
        public void Manufacture()
        {
            Console.WriteLine("Car Manufacturing");
         }
     }

     public class Bike : IVehicle
     {
         public void Manufacture()
         {
            Console.WriteLine("Bike Manufacturing");
         }
     }

     public static class factory
     {
         public static IVehicle GetVehicle(string name)
         {
            switch(name)
            {
                case "Car":
                    return new Car();
                case "Bike":
                    return new Bike();
                default:
                    throw new ArgumentException();
            }
        }
    }

    public class program
    {
        public static void Main()
        {
            Console.WriteLine("Please enter Car or Bike for manufacture");
            var vehicleName = Console.ReadLine();
            factory.GetVehicle(vehicleName).Manufacture();
            Console.ReadLine();
        }
    }

}

你能在这里消除我的误解吗?这段代码是工厂模式和策略模式的例子吗?先感谢您。

编辑

这是策略模式的一个例子吗?我刚刚编辑了 Program.cs

public class program
{
    public static void Main()
    {
        Console.WriteLine("Please enter Car or Bike for manufacture");
        var vehicleName = Console.ReadLine();
        var vehicle = factory.GetVehicle(vehicleName);


    }

    public void manufacture(IVehicle vehicle)
    {
        // assume that this method is in different class and method is calling with strategy as i understood.
        vehicle.Manufacture();
    }
}

标签: c#design-patterns

解决方案


我会说是的,该GetVehicle方法是一个名为simple factory的专用工厂模式的示例,并且您正在使用它返回的东西以使用策略模式的方式 - 调用代码与具体实现无关策略。


推荐阅读