设计模式之Inheritance versus Parameterized Types 继承和参数化类型
Another (not strictly object-oriented)technique for reusing functionality is through parameterized types, also known asgenerics (Ada, Eiffel) and templates (C++). This technique lets you define atype without specifying all the other types it uses. The unspecified types aresupplied as parameters at the point of use. For example, a List class can beparameterized by the type of elements it
contains. To declare a list of integers,you supply the type "integer" as a parameter to the List parameterized type. To declarea list of String objects, you supply the "String" type as a parameter.The language implementation will create a customized version of the List classtemplate for each type of element.
重用功能体的其他技术是参数化类型,也被称作泛型或模板。这种技术让你定义了一种指定的不是现在在用的类型。这个没有指定的类型在使用的时候通过提供参数
来弥补。例如,链表类可以通过它包含的元素类型被参数化。为了声明一个整形的链表,你指定了整形作为链表参数化的类型。为了声明一个字符串类型的链表对象,你指定了链表作为参数化的类型。语言的实现将会为每一个类型的元素创造客户指定的链表类模板。
Parameterized types give us a third way (inaddition to class inheritance and object composition) to compose behavior inobject-oriented systems. Many designs can be implemented using any of these threetechniques. To parameterize a sorting routine by the operation it uses to compareelements, we could make the comparison
1. an operation implemented by subclasses(an application of Template Method
(360),
2. the responsibility of an object that'spassed to the sorting routine
(Strategy (349), or
3. an argument of a C++ template or Adageneric that specifies the name of
the function to call to compare theelements.
在面向对象系统里,参数化类型给了我们第三种方式来构建行为(除了类的继承和对象的组合)。很多设计可以用这三种技术实现。我们可以做一个比较:
(1)通过子类来实现运算。(360页有一个应用的模板方法)
(2)对象的职责是保留了其储存路线。
(3)c++模板参数或ada 的泛型指定了被函数调用的元素的名字。
There are important differences betweenthese techniques. Object composition lets you change the behavior being composed atrun-time, but it also requires indirection and can be less efficient.Inheritance lets you provide default implementations for operations and letssubclasses override them. Parameterized types let you change the types that a classcan use. But neither inheritance nor
parameterized types can change at run-time.Which approach is best depends on your design and implementation constraints.
下面是这三种技术重要的不同。对象的组合会让你在运行时改变被组合的对象的行为。他也让命令变得间接和低效。继承提供了默认的运算的实现或让子类覆盖的实现。参数化类型会让你用可用的类型来改变类的类型。但是继承和参数化类型不能在运行时被改变。到底用那种方法来处理依靠你设计和实现的约束。
None of the patterns in this book concerns parameterized types, though we use them on occasion to customize a pattern's C++ implementation. Parameterized types aren't needed at all in a language like Smalltalk that doesn't have compile-time type checking
在这本书里没有一种模式关心参数化类型,尽管我们会用它在客户指定用c++模式实现的时候。像Smalltalk这些语言在一点也不需要在编译时不做类型检查的参数化类型的。