如何写出最优美的工厂模式
提问
如何写出最优美的工厂模式
回答
首先定义什么是最优美
最优美代表着他:面对新增开放,面对修改关闭实践
那么如何实现呢?
我选择使用特性 + 反射
public ICommand? BuildCommand(string[]? args)
{
if (args == null || args.Length != 2)
throw new ArgumentException("请输入正确的命令和参数");
ICommand? command = null;
var assembly = Assembly.GetExecutingAssembly();
if (!Equals(null, assembly))
{
var typeInfos = assembly.DefinedTypes.Where(t =>
t.CustomAttributes.Select(r => r.AttributeType).ToList().Contains(typeof(CommandAttribute)));
var typeInfo = typeInfos.FirstOrDefault(r => r.GetCustomAttributes(typeof(CommandAttribute)).Any(w => ((w as CommandAttribute)!).Name.Equals(args[0])));//.GetCustomAttribute(typeof(CommandAttribute)) as CommandAttribute;
if (!Equals(typeInfo, null))
{
if (typeInfo.FullName != null)
{
var serviceProvider = ServiceProviderHelper.GetInstance().ServiceProvider;
if (serviceProvider != null)
command = assembly.CreateInstance(typeInfo.FullName, true, BindingFlags.Default, null,
new object[]
{
args[1],
serviceProvider.GetService<IQualityControl>() ??
throw new InvalidOperationException()
}, null, null) as ICommand;
}
}
}
return command;
}
定义的特性
[AttributeUsage(AttributeTargets.Class)]
public class CommandAttribute : Attribute
{
public string Name { get; set; }
public CommandAttribute(string name)
{
Name = name;
}
}