工厂模式中使用的策略模式?

5

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

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();
    }
}

1
这可能更适合于软件工程。我认为这不是策略模式的一个例子,因为没有使用策略接口。所有东西都在工厂类中硬编码了。 - ProgrammingLlama
3
您在这里实现的是一个简单的工厂模式例子,而不是策略模式,正如上面的评论中John所述。为了更好地理解,请查看策略模式与工厂模式的比较 - vikscool
谢谢@John和vikscool。我已经编辑了问题,如果您能解决我的疑问。 - Darshit Gandhi
即使进行制造,这也不是策略模式。 - Johnny
@DarshitGandhi 如果你对我们的回答有任何疑问,请随时提出。 - michasaucer
2个回答

1
我会说是的,GetVehicle 方法是一个专门的工厂模式示例,称为简单工厂,您正在使用它返回的内容以策略模式使用的方式 - 调用代码对策略的具体实现不知情。

1
你的代码是带参数的工厂方法示例。你可以使用不带参数的工厂方法,这是更好的实践。
策略模式编辑算法,我喜欢从抽象类中实现策略,而不是接口。
例如,你的策略可能像这样:
首先,一个“策略”类。例如,它将计算燃料消耗:
public abstract class Strategy
{
    public abstract int FuelConsumption(int km);
}

现在,你需要编写你的策略。我会提供两个策略,一个用于快速驾驶,另一个用于缓慢驾驶:
public class FastDriving : Strategy
{
    //you need to override abstract methods from abstract class that
    // are mentioned in Strategy as acstract, or any else abstract class
    public override double FuelComsumption(int km) => km * fuelPer100Km;

    private int fuelPer100Km = 30;
}

public class SlowDriving : Strategy
{
    //same history as above
    public override double FuelComsumption(int km) => km * fuelPer100Km - 100;

    private int fuelPer100Km = 10;
    //u need to edit alghoritm to strategy be a strategy
}

现在,在每个车辆中,您都可以使用抽象类策略的属性:
public class Bike : IVehicle
 {
     public void Manufacture()
     {
        Console.WriteLine("Bike Manufacturing");
     }

     int i = 1000; //some propertys needed to calculate alghoritm

     // method in vehicle class that we use to strategy, to edit our alghoritm
     public int CaluculateFuelConsumption() => Strategy.FuelConsumption() - i;

     //here is a property of your strategy
     public Strategy strategy {get; set;};
 }

现在,您需要填充您的策略。如果您愿意,可以在类主体中完成,也可以在主函数中完成:
Strategy strategy = new FastDriving();
Strategy strategy = new SlowDriving();

但是你可以做得更好。
只需创建一个抽象类,例如Vehicle
public abstract class Vehicle 
{
    public Strategy strategy {get; set;};
}

然后,您的车辆可以看起来像这样:

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

     int i = 1000; //some propertys needed to calculate alghoritm

     // method in vehicle class that we use to strategy, to edit our alghoritm
     public int CaluculateFuelConsumption() => Strategy.FuelConsumption() - i;

     //We deleted Strategy, because abstract Car class have already Strategy
     //We dont need override non abstract method. Only abstract propertys
     //need to be overrided
   }  

现在,在您的主类中,您可以使用工厂方法创建汽车列表并附加“策略”。
List<Vehicle> vehicles= new List<Vehicle>();

foreach(Vehicle vehicle in vehicles)
    {
        //its not factory, but you can use factory for your post here
        switch(name)
        {
            case "Car":
                vehicle =  new Car();
            case "Bike":
                vehicle = new Bike();
            default:
                throw new ArgumentException();
        }
        //now, we populate strategy
        vehicle.strategy = new FastDriving():

    }

然后您可以通过一个循环计算所有燃料消耗:
 foreach(Vehicle vehicle in vehicles)       
        int fuel += vehicle.CalculateFuelConsumption();

我写的策略是一种PUSH策略。还有一种PULL策略。您可以在网上阅读相关内容。我相信,我的回答足以让您了解策略如何工作 :)

如果您想了解更多关于模式的信息,我建议您访问以下网站:

设计模式


1
整个故事中工厂模式在哪里? - Johnny
工厂模式不是一个例子。在第一个foreach中,他可以使用switch来填充“new Bike()”或“new Car()”中的汽车列表,视情况而定。 - michasaucer
1
好的,我编辑了我的回答。如果这对OP来说还不够,我可以从他的代码中制作一个工作示例。我相信他会通过我上面的代码明白如何做到这一点(我编辑了foreach,在其中使用策略填充汽车)。 - michasaucer
1
重点是他在学习,他选择的例子并不是很好,我宁愿建议制作一个 factory,例如接收 EnviromentFriendlyComuteFastComute 策略,然后分别返回自行车或汽车... - Johnny
1
好的,在下一次编辑中,我会仔细查看他的原始帖子。就我的回答状态而言,我相信他会更好地理解策略。我还提供了一个带有工作示例的策略回答。 - michasaucer
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接