f#中受保护的虚拟方法 [英] protected virtual methods in f#
问题描述
- F# does not support the definition of
protected
methods. Here it is explained why - F# replaces
virtual
methods withabstract
methods defined in abstract classes (see here).
我想知道是否有办法完全阻止从派生类外部访问 abstract
方法.
I was wondering if there is a way to prevent access to abstract
methods from outside the derived classes at all.
推荐答案
和 Patryk Ćwiek 一样,我也不认为这是可能的,但这里有一个替代方案:
Like Patryk Ćwiek, I also don't think it's possible, but here's one alternative:
从设计模式我们知道我们应该偏爱组合而非继承.根据我的经验,你可以用继承做的一切,你也可以用组合来做.例如,您始终可以用策略替换模板方法.
From Design Patterns we know that we should favour Composition over Inheritance. In my experience, everything you can do with Inheritance, you can also do with Composition. As an example, you can always replace Template Method with a Strategy.
模板方法是抽象方法的典型用法,但如果您将其替换为策略,则可以(某种程度上)对客户端隐藏它:
A Template Method is a typical use of an abstract method, but if you replace it with a Strategy, you can (sort of) hide it from clients:
type Foo(strategy : IBar) =
member this.CreateStuff() =
// 1. Do something concrete here
// 2. Use strategy for something here
// 3. Do something else concrete here
// 4. Return a result
Foo
的外部客户端无法调用 strategy
,从而实现与保护成员相同的目标.
No outside client of Foo
can invoke strategy
, so that accomplishes the same goal as making a member protected.
您可能会争辩说,Foo
的原始创建者可能会保留对 strategy
的引用,并且仍然可以调用它.确实如此,但受保护成员也并非真正完全隐藏,因为您通常可以从相关类派生,这使您能够调用受保护成员.
You may argue that the original creator of Foo
may keep a reference to strategy
, and will still be able to invoke it. That's true, but protected members aren't really completely hidden either, because you can often derive from the class in question, which enables you to invoke the protected member.
还有一点是,如果你把Foo
的创建者和Foo
的客户端分开,strategy
对客户端来说是不可用的.
Another point is that if you separate the creator of Foo
from the client of Foo
, the strategy
will be unavailable to the client.
这篇关于f#中受保护的虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!