Implementing a Custom Interface After we've defined our interface, we have to add it to all the classes that we want to use it with. We do this by adding the Implements keyword at the top of the class module: Implements IsortableObject
Figure 11-1 shows that as soon as we add that line to the class, the interface name appears in the object dropdown at the top-left of the code pane, just like an object on a userform.Figure 11-1. The Interface Appears in the Object Drop-Down
When the interface name is selected in that drop-down, the right-hand drop-down lists the methods and properties defined for that interface, as shown in Figure 11-2.Figure 11-2. With the Interface Selected, the Properties and Methods Appear in the Right-Hand Drop-Down
Clicking one of the methods adds an outline procedure to the code module, just as it does for a userform object's event. We just need to add code to that routine to return the value to use when sorting this type of object. The complete, sortable CAuthor class is shown in Listing 11-7, where the code to implement the ISortableObject interface has been highlighted.Listing 11-7. The Sortable CAuthor Class
'Name: CAuthor 'Description: Class to represent a book's author 'Allow this type of object to be sortable 'by the generic routine Implements ISortableObject Dim msAuthName As String Public Property Let AuthorName(sNew As String) msAuthName = sNew End Property Public Property Get AuthorName() As String AuthorName = msAuthName End Property 'Return the value to be used when sorting this object Private Property Get ISortableObject_SortKey() As Variant ISortableObject_SortKey = AuthorName End Property
Note that the name of the ISortableObject_SortKey routine is the concatenation of the interface name and the property name and that it is a Private property of the CAuthor class, so won't appear on the CAuthor interface. |