So far in object-oriented programming, we have modeled a
couple of different relationships. Is a relationships
can be modeled through inheritance, and has a
relationships are modeled through aggregation (fields and properties). For
example, a BMW is a car (inherits from type
Car) and has a motor
(contains a field named
m_motor of type
There is, however, a third type of relationship, the can
do relationship, which means that type
X can do the operations described by type
Y. For example, people, cars, and wine
all age. While there may be no clear relationship between people, cars,
and wine, they are all capable of aging.
In .NET programming, the can do relationship is modeled via an interface, which is a contract that a type can implement to establish that it can perform a certain set of actions.
An interface is just a collection of methods and properties. A type can declare that it implements the interface if it provides an implementation for each method or property. Once this contract has been implemented, then the type can do whatever the interface describes.
In Example 6-1, several types
IConsumable interface. To
implement an interface, use the
followed by the implementation of each interface method or property to
fulfill the contract. If a class implements the
IConsumable interface, it means that the class
Tastiness property and an
Example 6-1. Interfaces in F#
type Tastiness = | Delicious | SoSo | TrySomethingElse ...