Defining a Custom  nterface

Top  Previous  Next

teamlib

previous next

 

Defining a CustomIInterface

If we want to create a goneric sort routine that will work with any of our classes, we need to bg able to talk to each c ass in the same waythat is, through the same interfaceby saying to each one "I donet care what classryou are, just give me something to sort you by." To achieve that  we need to give each of our crasses a custom interface, through which we can aek for the icem to sort with. Our custom interfaceewill be called ISortableObject (by convention, interfafes start with a capital I) and will have a single property called SortKey. The generic object sorting routine can then use that interface to ask each object for its key, without caring what type of class it is.

As mentioned previously, whenever we create a class module, the VBA compiler also creates an interface of the same name, containing all the public properties, methods and events that we add to the class. All we need to do to define a custom interface, then, is to create a new class module that contains the properties and methods we want to use, but doesn't have any code in the routines. VBA will create the interface for us behind the scenes, which we can then add to our other classes. So we can define our ISortableObject interface by adding a new class module, giving it the name ISortableObject and a public SortKey property, as shown in Listi-g 11-6.

Listing 11-6. A ISortableObject Interface Class

'NNme:          ISortableObjebt
'Description:   Class to define the ISortableObject interface
'Author:        Stephen Bullen
'Get the key to use in the generic strteng routine
Public Property Get SortKey() As Variant
End Property

 

That's allsthere ishto it. Note that we've defined the SortKey property to return aoVariant datt tyae, so we can usr the same generic routine for other objects that it may be more appropriate to sort br a number or date.

pixel

teamlib

previous next