0

I started self learning design patterns from Design Patterns by Gang of Four

Parameterized types give us a third way (in addition to class inheritance and object composition) to compose behavior in object-oriented systems. Many designs can be implemented using any of these three techniques. To parameterize a sorting routine by the operation it uses to compare elements, we could make the comparison

  1. an operation implemented by subclasses (an application of Template Method (325)),
  2. the responsibility of an object that's passed to the sorting routine (Strategy (315)), or
  3. an argument of a C++ template or Ada generic that specifies the name of the function to call to compare the elements.

I looked up the template pattern, but was still wondering how the first way "make the comparison an operation implemented by subclasses (an application of Template Method)" is done?

I'd appreciate some example(s) in whichever OO language: C++, C#, Java, Python, ... Thanks.

1 Answers1

0

They're basically talking about something like this:

class Sorter {
  sort(Collection c) {
    ...
    if (isLessThan(a, b)) ...
    ...
  }

  abstract isLessThan();
}

class MyTypeSorter(Sorter) {
  isLessThan(a, b) {
    return a.member < b.member;
  }
}
Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38
  • Thanks. (1) Which language did you write your example in? Or the closest language? (2) Which OO languages (or their standard libraries) provide template implementation of sorting? Java, C++, C#, Python, ...? –  Sep 23 '17 at 20:32
  • 1) It's psuedo code :) Sort of a mix between Java and Python, I guess. 2) Java, C#, and Python use Strategy; C++ uses a template parameter. I don't know of any language that uses the template function pattern for this, and I'll admit it sounds like a weird choice given the alternatives. – Yam Marcovic Sep 24 '17 at 07:24