我目前正在使用一个 C# 类,它公开了一些 lambda [实例] 方法,这些方法用作同名静态方法的包装器。
这是一个示例片段:
public class UserUI : DataUI
{
// FYI: the `Context` object here is inherited from the `DataUI` base class
public string GetUserId() => GetUserId(Context);
public static string GetUserId(IDataUIContext context)
{
// ... logic here for pulling id from `context` ...
return userId;
}
}
我想知道:这样的设计模式有名字吗?
此外,是否可以使用类属性而不是实例方法/lambda 来完成相同的功能?
像这样:
public class UserUI : DataUI
{
public string GetUserId => GetUserId(Context);
public static string GetUserId(IDataUIContext context)
{
// ... logic here for pulling id from `context` ...
return userId;
}
}
如果是这样,使用属性/吸气剂之间是否有任何明显的区别? (显然,除了必须调用的方法而不是像字段一样访问)
这是一种设计模式吗?这不是经典的 GoF,但总的来说,这只是 部分应用,这是许多函数式编程语言众所周知的功能。
在流派中,您可以将任何类型为
public static string GetUserId(IDataUIContext context)
的过程视为(如果您删除 static
关键字)单方法接口的实现,该方法
public interface IMyInteface
{
string GetUserId(IDataUIContext context)
}
对应于
Func<IDataUIContext, string>
。如果您随后定义一个封闭输入 (IDataUIContext
) 的 lambda 表达式,那么您本质上就拥有了一个 string
值。简而言之,这就是部分应用。
对象只是闭包,因此,
GetUserId
方法实际上可以被视为函数或对象。