我希望能够使用这种代码实例化我的应用程序中的任何对象:
SmartForm smartForm = SmartForm.Create("id = 23");
Customer customer = Customer.Create("id = 222");
我现在正在讨论如果该对象不存在 Create() 应该返回什么。
如果 Create() 返回一个空对象,那么这是一种“空模式”,我仍然可以在我的应用程序中传递该对象并调用它的方法,这使得使用此模型进行编程变得方便和容易
如果 Create() 返回null,那么我需要在每次实例化后检查对象是否等于 null ,这使得编程有点乏味但更明确。这样做的一个问题是,如果您忘记检查 null,您的应用程序可能会在您不知道自己没有检查 null 的情况下工作很长时间,然后突然中断
如果 Create()抛出异常,它基本上与返回 null 相同,但通过让您为每个实例化创建一个 try、next、finally 块,使编程更加乏味,但是您可以抛出各种类型的异常(您可以) t 与 null 解决方案)可能会冒泡,以便您可以更明确地处理 UI 上的深层错误,所以我认为这是最强大的解决方案,尽管会产生 try/catch 代码膨胀
所以这似乎是一个轻盈/稳健的权衡。有没有人有过这样的决策经验?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestFactory234.Models
{
public class SmartForm : Item
{
public string IdCode { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int LabelWidth { get; set; }
public SmartForm() { }
private SmartForm(string loadCode)
{
_loadCode = loadCode;
TryToInstantiateFromDatabase();
}
public static SmartForm Create(string loadCode)
{
SmartForm smartForm = new SmartForm(loadCode);
if (!smartForm.IsEmpty())
{
return smartForm;
}
else
{
return null;
}
}
}
}