这个设计模式的名称是什么(通过委托向协作者公开私有方法)?
类通过委托向协作者公开私有方法或属性的设计模式的名称是什么?这是 C# 语言的内容,但也可能与其他语言相关。
例如:
class Foo
{
public int X
{
get;
private set;
}
public void UpdateX(Bar bar)
{
bar.UpdateX(x => this.X = x);
}
}
class Bar
{
public void UpdateX(Action<int> setter)
{
setter(7);
}
}
Foo foo = new Foo();
Bar bar = new Bar();
foo.UpdateX(bar);
我认为这在状态模式中很有用,允许状态更新其上下文,而不需要上下文通过其公共接口公开内容,或在上下文类中嵌套状态类。
What is the name for the design pattern where a class exposes a private method or property to a collaborator via a delegate? This is in C#, but may be relevant to other languages too.
For example:
class Foo
{
public int X
{
get;
private set;
}
public void UpdateX(Bar bar)
{
bar.UpdateX(x => this.X = x);
}
}
class Bar
{
public void UpdateX(Action<int> setter)
{
setter(7);
}
}
Foo foo = new Foo();
Bar bar = new Bar();
foo.UpdateX(bar);
I think this would be useful in the state pattern to allow states to update their contexts without requiring the context to expose stuff via its public interface, or nest state classes within the context class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我在这里没有看到任何模式,但它破坏了封装。
如果您有一个只读属性,那么为什么您要尝试规避它。
i don't see any pattern here but its a break of encapsulation.
if you are having a readonly property so why you are trying circumvent it.
策略模式
或状态模式
Strategy Pattern
orState Pattern
委托是一种设计模式。
Delegation is a design pattern.
这与 Memento 模式非常相似,后者对于存储和操作状态确实很有用。
它还具有依赖注入或委托的元素。
也许比我更有经验的人会认出它的真名。
以下是有关 Memento 模式的一些信息:
维基百科:Memento
以及依赖注入模式:
维基百科:依赖注入
This has striking similarity to the Memento pattern, which is indeed useful for storing and manipulating states.
It also has elements of Dependency Injection or Delegation.
Perhaps someone more seasoned than I will recognize it by it's true name.
Here is some information on the Memento pattern:
Wikipedia: Memento
And the Dependency Injection pattern:
Wikipedia: Dependency Injection
我将选择 Double Dispatch,价格为 200。并且正在向访客模式迈进。
我还认为这不会破坏封装,只是因为 Foo 定义了委托。
I'll take Double Dispatch for 200. And well on your way to the visitor pattern.
I would also argue that this doesn't break encapsulation, simply because Foo defines the delegate.