c# - 工厂模式中使用的策略模式?
问题描述
我正在使用工厂模式编写代码。在 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();
}
}
解决方案
我会说是的,该GetVehicle
方法是一个名为simple factory的专用工厂模式的示例,并且您正在使用它返回的东西以使用策略模式的方式 - 调用代码与具体实现无关策略。
推荐阅读
- azure - 如何使用 Azure Data Bricks 使用 REST API 端点?
- reactjs - 为什么axios不向asp.core api提交数据
- python - 使用 boto3 在 python 中使用另一个现有表的结构创建 DynamoDB 表时出错
- javascript - javascript:单击编辑时更新文本框中的所有元素
- javascript - Javascript 结合来自 3 个文件的 HTML 来创建表格
- matlab - 为什么solve()会抛出这个结果 Empty sym: 0-by-1 并且无法得到正确的结果
- c++ - 带堆栈的 DFS 在有向、非循环、未加权图中查找某个节点的最长路径长度
- vue.js - 天蓝色地图不会在正确的位置渲染标记
- java - 我的 Java 代码中发生了什么使答案是否定的?
- python - GUI 中的“交互式”图形