Design by Abstraction (Continuation) CS 3331 Spring 2005
Outline Design Patterns Template method Strategy pattern Factory pattern CS 3331
Template Methods Intent Participants To define the skeleton of an algorithm by deferring some steps to subclasses To allow subclasses to redefine certain steps Participants Generic Class defines abstract hook methods and implements template methods Concrete Class implements hook methods GenericClass templateMethod() hookMethod1() hookMethod2() ConcreteClass … CS 3331
Template Methods (Cont.) Terminology Template methods: methods containing hook methods Hook methods: placeholders for the behaviour to be implemented differently by subclasses Frozen spots: fixed behaviours of generic classes represented by template methods Hot spots: changeable behaviours of generic classes represented by hook methods CS 3331
Example Complex numbers Rectangular Polar imaginary (x, y) (r, a) r y real imaginary Polar (r, a) r a CS 3331
Example Template Methods Hook Methods ComplexNumber add() mul() realPart() imaginaryPart() magnitude() angle() RectangularComplex PolarComplex Template Methods Hook Methods CS 3331
Strategy Design Pattern Intent To define a family of algorithms, encapsulate each one, and make them interchangeable Participants Context maintains references to Strategy objects Strategy declares a common interface to all supported algorithms ConcreteStrategy implements the algorithm using the Strategy interface Context contextMethod() Strategy ConcreteStrategyA algorithm() alogorithm() ConcreteStrategyB CS 3331
Factory Design Pattern Intent To decouple object creation from its use and to support different way of creating objects To define an interface for creating objects but let subclasses decide which class to instantiate and how Participants Abstract Factory defines a factory method that returns a Product object ConcreteFactory overrides the factory method to return an instance of ConcreteProduct Product defines an interface of the objects that the factory will create ConcreteProduct implements the product interface Product AbstractFactory makeProduct() creates ConcreteFactory makeProduct() ConcreteProuct CS 3331
Example Complex numbers Complex ComplexFactory makeComplext() PolarFactory makeComplex() PolarComplex creates RectangularFactory makeComplex() RectangularComplex creates CS 3331