CSC/ECE 517 Fall 2007/wiki1b 8 sa: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(17 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= The Strategy Design Pattern, comparing a dynamic OO language to a static OO languaje =
= The Strategy Design Pattern, comparing a dynamic OO language to a static OO language =


In this page we explore the differences in implementation and design of the Strategy design pattern between the dynamic Object-Oriented language Ruby and the static Object-Oriented language Java.
In this page we explore the differences in implementation and design of the Strategy design pattern between the dynamic Object-Oriented language Ruby and the static Object-Oriented language Java.
Line 7: Line 7:
== Design Patterns ==
== Design Patterns ==


A design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern is neither a finished design nor a solution that can be transformed directly into code. It is a template on how to solve a problem that can be used in many different situations. Design patterns are more often use in Object oriented designs as they typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.  
A [http://en.wikipedia.org/wiki/Design_pattern_(computer_science) design pattern] is a general repeatable solution to a commonly occurring problem in software design. A design pattern is neither a finished design nor a solution that can be transformed directly into code. It is a template on how to solve a problem that can be used in many different situations. Design patterns are more often use in [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] designs as they typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.  


Note: Algorithms are not design patterns, algorithms solve computational problems and design patterns solve design problems.
Note: Algorithms are not design patterns, algorithms solve computational problems and design patterns solve design problems.


== Strategy Pattern ==
== Strategy Pattern ==
The Strategy Design Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.  
The Strategy Design Pattern defines a family of [http://en.wikipedia.org/wiki/Algorithm algorithms], encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.  


The Strategy pattern lets one build software as a loosely coupled collection of interchangeable parts, in contrast to a monolithic, tightly coupled system. That loose coupling makes the software much more extensible, maintainable, and reusable. The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application.
The Strategy pattern lets one build software as a loosely coupled collection of interchangeable parts, in contrast to a monolithic, tightly coupled system. That loose coupling makes the software much more extensible, maintainable, and reusable. The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application.


=== Structure ===
=== Structure ===
[[Image:Strategy-Example.jpg||Sort using Strategy]]


Normally there are 3 types of classes and or objects that participate in a strategy pattern implementation
Normally there are 3 types of classes and or objects that participate in a strategy pattern implementation
Line 30: Line 32:
: may define an interface that lets Strategy access its data.
: may define an interface that lets Strategy access its data.


 
For example lets take the general case of sorting a list. One may wish to use different sort strategies based on the length of the list as performance of these sort algorithms vary depending on the size of the list. Here SortStrategy will be the common interface to all supported sort algorithms (like [http://en.wikipedia.org/wiki/Quicksort QuickSort], [http://en.wikipedia.org/wiki/Merge_sort MergeSort], [http://en.wikipedia.org/wiki/Bubble_sort Bubble Sort] etc.,) and SortedList will be the context that lets Strategy access the list and operate on it.
[[Image:Strategy-Example.jpg||Sort using Strategy]]
 
 
For example lets take the general case of sorting a list. One may wish to use different sort strategies based on the length of the list as performance of these sort algorithms vary depending on the size of the list. Here SortStrategy will be the common interface to all supported sort algorithms (like QuickSort, MergeSort, SyncSort etc.,) and SortedList will be the context that lets Strategy access the list and operate on it.


=== Merits ===
=== Merits ===
Line 47: Line 45:


=== Demerits ===
=== Demerits ===
Note: Most of these demerits are specific to statically typed languages like Java. Use of dynamic object oriented languages like Ruby can help bypass these demerits


# The application must be aware of all the strategies to select the right one for the right situation.
# The application must be aware of all the strategies to select the right one for the right situation.
# Strategy and Context classes may be tightly coupled. The Context must supply the relevant data to the Strategy for implementing the algorithm and sometimes, all the data passed by the Context may not be relevant to all the Concrete Strategies.
# Context and the Strategy classes normally communicate through the interface specified by the abstract Strategy base class. Strategy base class must expose interface for all the required behaviors, which some concrete Strategy classes might not implement.
# Context and the Strategy classes normally communicate through the interface specified by the abstract Strategy base class. Strategy base class must expose interface for all the required behaviors, which some concrete Strategy classes might not implement.
# In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one.
# In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one.
Line 70: Line 69:
To demonstrate further let us consider an application that manages songs and playlists, and helps you copy/synchronize songs to you compact MP3 player or Mobile phone. The application accepts a playlist which has a catalog of MP3 files in different directories.  
To demonstrate further let us consider an application that manages songs and playlists, and helps you copy/synchronize songs to you compact MP3 player or Mobile phone. The application accepts a playlist which has a catalog of MP3 files in different directories.  


Let critical actions performed on the files in playlist be renaming, copying or reencoding. Let each file to be copied/synchronized be represented by a <code>FileJob</code> object containing the source and destination paths. The actual action (rename/copy/reencode) that needs to be performed is given to the <code>FileJob</code> as an object implementing the <code>FileOperation</code> interface (which is the strategy). The application then has three different file operations: <code>CopyOperation</code>, <code>RenameOperation</code> and <code>ReencodeOperation</code> (which are the implementations). Here the file under the operations takes the role of context.
Let critical actions performed on the files in playlist be renaming, copying or reencoding. Let each file to be copied/synchronized be represented by a <code>FileJob</code> object instance containing the source and destination paths. The actual action (rename/copy/reencode) that needs to be performed is given to the <code>FileJob</code> object as an instance of a class implementing the <code>FileOperation</code> interface. The application then has three different file operations: <code>CopyOperation</code>, <code>RenameOperation</code> and <code>ReencodeOperation</code>. Therefore, <code>FileJob</code> is the context class, the <code>FileOperation</code> interface is the strategy, and <code>CopyOperation</code>, <code>RenameOperation</code> and <code>ReencodeOperation</code> are concrete strategies.




Line 80: Line 79:
== Java's Solution ==
== Java's Solution ==


Here is the Java implementation of the playlist synchronization application.
Here is the [http://java.sun.com/ Java] implementation of the playlist synchronization application.


<pre>
<pre>
Line 151: Line 150:
}
}
</pre>
</pre>


== Ruby's Solution ==
== Ruby's Solution ==


Here is the Ruby implementation of the playlist synchronization application.
Here is the [http://www.ruby-lang.org/en/ Ruby] implementation of the playlist synchronization application.


<pre>
<pre>
Line 211: Line 209:
| Algorithms for strategies need to be defined at compile time
| Algorithms for strategies need to be defined at compile time
| New algorithms for strategies can be created on the fly using  
| New algorithms for strategies can be created on the fly using  
meta programming
[http://en.wikipedia.org/wiki/Meta_programming meta programming]
|-
|-
| Difficult to include one algorithm under several strategies  
| Difficult to include one algorithm under several strategies  
| Unbounded polymorphism/Mixins makes one algorithm reusable  
| Unbounded [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism]/Mixins makes one algorithm reusable  
under several strategies
under several strategies
|-
|-
Line 222: Line 220:
| Syntactic regular expression support not available.
| Syntactic regular expression support not available.
| Interesting algorithm use cases can be constructed using the
| Interesting algorithm use cases can be constructed using the
syntactic regular expression support for Ruby
syntactic [http://en.wikipedia.org/wiki/Regular_expression regular expression] support for Ruby
|-
|-
|}
|}
Line 230: Line 228:
The comparison yields interesting insights into the advantages of Ruby over Java. Clearly Ruby has much higher edge in using OO design patterns like strategy over any other statically typed language.
The comparison yields interesting insights into the advantages of Ruby over Java. Clearly Ruby has much higher edge in using OO design patterns like strategy over any other statically typed language.


# Ruby's code is succint, Java requires more boilerplate code due to the static nature of the language
# Ruby's code is succinct, Java requires more boilerplate code due to the static nature of the language
# Closures make it trivial to add parameters to the stategy implementations, in Java parameters to strategies must be instance or class variables
# Closures make it trivial to add parameters to the strategy implementations, in Java parameters to strategies must be instance or class variables
# Unbounded polymorphism/mixins of Ruby provides better code reusability
# Unbounded polymorphism/[http://en.wikipedia.org/wiki/Mixins mixins] of Ruby provides better code reusability
# Highly dynamic strategies can be constructed using meta programming features of Ruby
# Highly dynamic strategies can be constructed using meta programming features of Ruby
# New algorithms can be evaluated dynamically with ease
# New algorithms can be evaluated dynamically with ease

Latest revision as of 01:15, 11 October 2007

The Strategy Design Pattern, comparing a dynamic OO language to a static OO language

In this page we explore the differences in implementation and design of the Strategy design pattern between the dynamic Object-Oriented language Ruby and the static Object-Oriented language Java.

Definitions

Design Patterns

A design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern is neither a finished design nor a solution that can be transformed directly into code. It is a template on how to solve a problem that can be used in many different situations. Design patterns are more often use in Object-oriented designs as they typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.

Note: Algorithms are not design patterns, algorithms solve computational problems and design patterns solve design problems.

Strategy Pattern

The Strategy Design Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

The Strategy pattern lets one build software as a loosely coupled collection of interchangeable parts, in contrast to a monolithic, tightly coupled system. That loose coupling makes the software much more extensible, maintainable, and reusable. The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application.

Structure

Sort using Strategy

Normally there are 3 types of classes and or objects that participate in a strategy pattern implementation

  • Strategy
declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy
  • ConcreteStrategy
implements the algorithm using the Strategy interface
  • Context
is configured with a ConcreteStrategy object
maintains a reference to a Strategy object
may define an interface that lets Strategy access its data.

For example lets take the general case of sorting a list. One may wish to use different sort strategies based on the length of the list as performance of these sort algorithms vary depending on the size of the list. Here SortStrategy will be the common interface to all supported sort algorithms (like QuickSort, MergeSort, Bubble Sort etc.,) and SortedList will be the context that lets Strategy access the list and operate on it.

Merits

  1. A family of algorithms can be defined as a class hierarchy and can be used interchangeably to alter application behavior without changing its architecture.
  2. By encapsulating the algorithm separately, new algorithms complying with the same interface can be easily introduced.
  3. The application can switch strategies at run-time.
  4. Strategy enables the clients to choose the required algorithm, without using a "switch" statement or a series of "if-else" statements.
  5. Data structures used for implementing the algorithm are completely encapsulated in Strategy classes. Therefore, the implementation of an algorithm can be changed without affecting the Context class.
  6. Strategy Pattern can be used instead of sub-classing the Context class. Inheritance hardwires the behavior with the Context and the behavior cannot be changed dynamically.
  7. The same Strategy object can be strategically shared between different Context objects. However, the shared Strategy object should not maintain states across invocations.

Demerits

Note: Most of these demerits are specific to statically typed languages like Java. Use of dynamic object oriented languages like Ruby can help bypass these demerits

  1. The application must be aware of all the strategies to select the right one for the right situation.
  2. Context and the Strategy classes normally communicate through the interface specified by the abstract Strategy base class. Strategy base class must expose interface for all the required behaviors, which some concrete Strategy classes might not implement.
  3. In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one.
  4. Since, the Strategy object is created by the application in most cases; the Context has no control on lifetime of the Strategy object. However, the Context can make a local copy of the Strategy object. But, this increases the memory requirement and has a sure performance impact.

Related Patterns

Command and Bridge are two closely related patterns to Strategy.

  • A Command pattern encapsulates a single action, therefore it tends to have a single method with a rather generic signature. It often is intended to be stored for a longer time and to be executed later. Strategy, in contrast, is used to customize an algorithm. A strategy might have a number of methods specific to the algorithm. Most often strategies will be instantiated immediately before executing the algorithm, and discarded afterwards.
  • Bridge pattern is meant for structure, whereas the Strategy pattern is meant for behavior. The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

Alternatives

In some programming languages, such as those without polymorphism, the issues addressed by strategy pattern are handled through forms of reflection, such as the native function pointer or function delegate syntax.

Real World Case Study

To demonstrate further let us consider an application that manages songs and playlists, and helps you copy/synchronize songs to you compact MP3 player or Mobile phone. The application accepts a playlist which has a catalog of MP3 files in different directories.

Let critical actions performed on the files in playlist be renaming, copying or reencoding. Let each file to be copied/synchronized be represented by a FileJob object instance containing the source and destination paths. The actual action (rename/copy/reencode) that needs to be performed is given to the FileJob object as an instance of a class implementing the FileOperation interface. The application then has three different file operations: CopyOperation, RenameOperation and ReencodeOperation. Therefore, FileJob is the context class, the FileOperation interface is the strategy, and CopyOperation, RenameOperation and ReencodeOperation are concrete strategies.



Java's Solution

Here is the Java implementation of the playlist synchronization application.

import java.util.ArrayList;

// This is the Strategy interface
interface FileOperation {
  public void Run(String from, String to);
}

// These are the three different implementations
class CopyOperation implements FileOperation {
  public void Run(String from, String to) {
    System.out.println("Copy " + from + " to " + to + ".");
  } 
}

class ReencodeOperation implements FileOperation {
  private int bitRate_; // In kbps

  ReencodeOperation(int bitRate) {
    bitRate_ = bitRate;
  }

  public void Run(String from, String to) {
    System.out.println("Reencode " + from + " to " + to + " at " + bitRate_ + "kbps.");
  } 
}

class RenameOperation implements FileOperation {
  public void Run(String from, String to) {
    System.out.println("Rename " + from + " to " + to + ".");
  } 
}

// This is the context class
class FileJob {
  String from_;
  String to_;
  FileOperation op_;

  public FileJob(String from, String to, FileOperation op) {
    from_ = from;
    to_ = to;
    op_ = op;
  }

  void Run() {
    op_.Run(from_, to_);
  }
}

// Sample code
class Test {
  public static void main(String[] args) {
    ArrayList<FileJob> jobs = new ArrayList<FileJob>();

    FileOperation copyOp = new CopyOperation();
    FileOperation renameOp = new RenameOperation();
    FileOperation reencodeOp = new ReencodeOperation(128); // kbps
      
    jobs.add(new FileJob("file1", "file2", copyOp));
    jobs.add(new FileJob("file3", "file4", renameOp));
    jobs.add(new FileJob("file5", "file6", reencodeOp));

    for (FileJob j : jobs) {
      j.Run();
    }
  }
}

Ruby's Solution

Here is the Ruby implementation of the playlist synchronization application.

# To give the file operation invocation a better name we define an alias, note
# that this is optional, one can just use 'call', but it is better to adapt
# the name to the problem domain
class FileOperation < Proc
  alias_method :run, :call
end

# These are the strategies
copyOp     = FileOperation.new { |from, to| puts "Copy #{from} to #{to}." }
renameOp   = FileOperation.new { |from, to| puts "Rename #{from} to #{to}." }
bitRate = 128 # kbps
reencodeOp = FileOperation.new { |from, to| puts "Reencode #{from} to #{to} at #{bitRate}kbps." }

# This is the context class
class FileJob
  def initialize(from, to, op)
    @from = from
    @to = to
    @op = op
  end

  def run
    @op.run(@from, @to)
  end
end

# The same test as the Java implementation
jobs = Array.new

jobs << FileJob.new("file1", "file2", copyOp);
jobs << FileJob.new("file3", "file4", renameOp);
jobs << FileJob.new("file5", "file6", reencodeOp);

jobs.each { |j| j.run() }

Java versus Ruby

Comparison

Let us perform a comparison to better understand the implementation

Java's Strategy Implementation Ruby's Strategy Implementation
An interface declaration, defines a common interface to the

algorithm family

No interface declaration required
A class is required for each strategy implementation No classes required, closures are good enough
Algorithms for strategies need to be defined at compile time New algorithms for strategies can be created on the fly using

meta programming

Difficult to include one algorithm under several strategies Unbounded polymorphism/Mixins makes one algorithm reusable

under several strategies

Difficult to evaluate new algorithms inside strategies New algorithms can be evaluated dynamically using eval
Syntactic regular expression support not available. Interesting algorithm use cases can be constructed using the

syntactic regular expression support for Ruby

Where Ruby wins?

The comparison yields interesting insights into the advantages of Ruby over Java. Clearly Ruby has much higher edge in using OO design patterns like strategy over any other statically typed language.

  1. Ruby's code is succinct, Java requires more boilerplate code due to the static nature of the language
  2. Closures make it trivial to add parameters to the strategy implementations, in Java parameters to strategies must be instance or class variables
  3. Unbounded polymorphism/mixins of Ruby provides better code reusability
  4. Highly dynamic strategies can be constructed using meta programming features of Ruby
  5. New algorithms can be evaluated dynamically with ease

References

Books

  1. Programming Ruby: The programmatic programmer’s guide
  2. Head First Design Patterns

Links

  1. Strategy Pattern - Data and Object Factory
  2. Design Patterns - Wikipedia
  3. Strategy for Success - Java World

See Also

  1. Strategy Design Pattern and Open-Closed Principle
  2. Strategy Pattern for PHP Explained


Note: Santthosh (sbselvad@ncsu.edu) and Agustin (agusvega@nc.rr.com) edited this page.