“获取或创建” - 这个习语有固定的名称吗?
好吧,考虑一下我们大多数人都多次使用过的这个常见习语(我假设):
class FooBarDictionary
{
private Dictionary<String, FooBar> fooBars;
...
FooBar GetOrCreate(String key)
{
FooBar fooBar;
if (!fooBars.TryGetValue(key, out fooBar))
{
fooBar = new FooBar();
fooBars.Add(key, fooBar);
}
return fooBar;
}
}
它有任何既定的名称吗?
(是的,它是用 C# 编写的,但它可以“轻松”转移到 C++。因此有了这个标签。)
Ok, consider this common idiom that most of us have used many times (I assume):
class FooBarDictionary
{
private Dictionary<String, FooBar> fooBars;
...
FooBar GetOrCreate(String key)
{
FooBar fooBar;
if (!fooBars.TryGetValue(key, out fooBar))
{
fooBar = new FooBar();
fooBars.Add(key, fooBar);
}
return fooBar;
}
}
Does it have any kind of established name?
(Yes, it's written in C#, but it can be "easily" transferred to C++. Hence that tag.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我总是调用此类函数
obtainSomething()
。I always call such functions
obtainSomething()
.这在某种程度上取决于你这样做的原因——我见过的习惯用法被称为记忆、缓存、按需初始化、第一次使用时创建。通常我将该方法称为“ensureFoo”而不是“GetOrCreate”
It sort of depends why you're doing it - the idiom is one I've seen be called memoization, caching, initialisation on demand, create on first use. Normally I call the method "ensureFoo" rather than "GetOrCreate"
延迟加载
http://en.wikipedia.org/wiki/Lazy_loading
Lazy Loading
http://en.wikipedia.org/wiki/Lazy_loading
我不确定高级模式的整体编程名称,但 Perl 有这种奇妙的行为,称为 Autovivification - 即,当您查询哈希中不存在的键的值时,自动创建具有未定义值的哈希(映射)键。
I'm unsure of overall programming name for the high level pattern, but Perl has this wonderful behavior called Autovivification - namely, automatically creating hash (map) key with undefined value when you're querying the value of non-existing key in the hash.