Section 2.8. Templates


2.8. Templates

Just as interfaces allow you to provide specifications for objects your class will interact with, UML allows you to provide abstractions for the type of class your class may interact with. For example, you can write a List class that can hold any type of object (in C++ this would probably be a void*, in Java and C# it would probably be an Object). However, while you wanted your List class to be able to support any type of object, you want all of the objects in a given list to be of the same type. UML allows you to create and specify these kinds of abstractions using templates.

You can indicate that a class is a templated (also called parameterized) class by drawing a dashed rectangle in the upper-right corner of the class. For each element you would like to template, you need to specify a name to act as a placeholder for the actual type. Write the placeholder name in the rectangle. Figure 2-34 shows an example of a List class that can support any type.

Figure 2-34. A templated List class


This example uses ElementType as the name of the templated type for clarity. In practice, this is often abbreviated to just T.


You can have multiple templated types within a single class; just separate the type names with a comma (,). If you need to restrict the types the user may substitute, show that with a colon (:) followed by the type name. Figure 2-35 shows a more complicated version of the List class that requires a Sorter along with the type of object to store in the list.

Figure 2-35. A templated class with type restrictions


Specifying restrictions on a type that may be used is functionally similar to specifying an interface for a templated member, except that the user may be able to further restrict an instance of your class by specifying a subclass of your type.

When a user creates an instance of a List, she needs to specify the actual type to use in place of ElementType. This is called binding a type to a template. You show binding with the keyword «bind», followed by a type specification using the following syntax:

 < TemplatedType -> RealType > 

You can use the binding syntax whenever you refer to a templated class to indicate you want to use a bound version of that class. This is called explicit binding. For example, Figure 2-36 shows a subclass of List called EmployeeList that binds the ElementType of List to a class named Employee.

Figure 2-36. Explicit template binding


The bind keyword also indicates what types should be used with an instance of a template. This is called implicit binding and is shown in Figure 2-37.

Figure 2-37. Implicit template binding





UML 2.0 in a Nutshell
UML 2.0 in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596007957
EAN: 2147483647
Year: 2005
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net