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).
我想知道是否有一种方法可以阻止派生类外部访问抽象
方法。
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
可以调用策略
,从而实现与保护成员相同的目标。
No outside client of Foo
can invoke strategy
, so that accomplishes the same goal as making a member protected.
您可能会争辩说原始的 Foo
的创建者可以保留对策略
的引用,并且仍然可以调用它。是的,但是受保护的成员也没有真正被完全隐藏,因为您经常可以从有问题的类中派生出来,这使您可以调用受保护的成员。
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
的客户端分开,则
对客户端不可用。
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屋!