CSC/ECE 517 Fall 2010/ch3 3h az: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(78 intermediate revisions by 2 users not shown)
Line 1: Line 1:
=Objective=
=Objective=
Objective of this Wiki Chapter is that the reader should be get an overview of
After reading this Wiki Chapter,the reader should get an overview of


# Strategy pattern, when and how to use strategy pattern.
# What is a [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch3_3h_az strategy pattern], when and how to use it.
# Implementation of strategy pattern in Dynamic, Static object oriented language by going through our example.
# Implementation of strategy pattern in Dynamic and Static object oriented languages.


=Introduction=
=Introduction=
A design pattern is a general reusable solution to a commonly occurring  problem in software design.
A [http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 design pattern] is a general reusable solution to a commonly occurring  problem in software design[[#References|<sup>3</sup>]].
Strategy Pattern in one such pattern which helps to use multiple algorithms interchangeably to reduce     
Strategy Pattern in one such pattern which helps the user to use multiple algorithms interchangeably to reduce     
multiple conditions statements. This helps in making the code more maintainable.
multiple conditional statements. This helps in making the code more maintainable.


The intent of Strategy pattern would be to define a family of algorithms, encapsulate each one, and  
The intent of Strategy Pattern is to define a family of algorithms,[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulate] each algorithm, and  
make them interchangeable.  Strategy lets the algorithm vary independently from clients that use it.
make them interchangeable.  Strategy lets the algorithm vary independently from clients that use it.
As an algorithm evolves to handle more and more situations, it can become very complex and difficult  
As an algorithm evolves to handle more and more situations, it can become very complex and difficult  
to maintain, Strategy pattern can be used to resolve this situation.
to maintain, Strategy pattern can be used to resolve this situation[[#References|<sup>8</sup>]].


The Strategy pattern is different form the Bridge and State pattern. Listed below are the differences and when  to use each of them-
==Components in the implementation of a strategy pattern==
The components in the implementation of a strategy pattern are[[#References|<sup>1</sup>]]:
 
'''''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.
 
==When to use Strategy Pattern==
# Many related classes differ only in their behavior.
# You need different variants of an algorithm.  For example, defining different algorithms based on  space-time tradeoffs.
# A class defines many behaviors, and these appear as multiple conditional statements in its operations.Instead, move related conditional branches into their own Strategy class.
==Related Patterns==
[http://en.wikipedia.org/wiki/Bridge_pattern Bridge] and [http://en.wikipedia.org/wiki/State_pattern State] pattern are related patterns to the strategy pattern. Listed below are the key differences[[#References|<sup>6</sup>]] [[#References|<sup>7</sup>]]-


{| border="1" cellspacing="0" cellpadding="5" align="center"
{| border="1" cellspacing="0" cellpadding="5" align="center"
Line 26: Line 43:
| The Bridge pattern deals with HOW you deal with multiple implementations. The Bridge pattern is meant for structure.
| The Bridge pattern deals with HOW you deal with multiple implementations. The Bridge pattern is meant for structure.
| The State pattern deals with HOW you switch between different states/implementations
| The State pattern deals with HOW you switch between different states/implementations
|-
| It defines a family of algorithms, encapsulate each one and make them interchangeable.
| It allows an object to alert its behavior when its internal state changes. The object will appear to change its class.The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction.
| It allows an object to alert its behavior when its internal state changes. The object will appear to change its class.
|-
|-
| One way to implement the Strategy pattern is to use the Bridge pattern approach or the State pattern approach, but the strategy pattern can also be  
| One way to implement the Strategy pattern is to use the Bridge pattern approach or the State pattern approach, but the strategy pattern can also be  
Line 32: Line 53:
| You cannot use the strategy pattern to implement state pattern.
| You cannot use the strategy pattern to implement state pattern.
|}
|}
==When to use Strategy Pattern==
# Many related classes differ only in their behavior.
# You need different variants of an algorithm.  For example, defining different algorithms based on  space-time tradeoffs.
# A class defines many behaviors, and these appear as multiple conditional statements in its operations.Instead, move related conditional branches into their own Strategy class.
==Components in the implementation of a Strategy pattern:==
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.


=Illustration of Strategy pattern through real world example=
=Illustration of Strategy pattern through real world example=
To illustrate strategy pattern let’s consider this example of basic file transfer scenario,
To illustrate the strategy pattern, let us consider an example of a basic file transfer scenario,
where we want to compress the file before transmission.  
where we want to compress the file before transmission.  
File compression can be achieved by different algorithms for different types of file.
Image files and text files are compressed by using different compression algorithms.
Image files and text files can be compressed by different algorithms,
Here we would  like to demonstrate how this algorithm can be encapsulated in objects and  
here we would  like demonstrate how this algorithm can be encapsulated and  
how these objects can be selected without using the conditional statements.
helps in selecting the algorithms without the conditional statements.


The following UML class diagram captures the scenario we are illustrating:
The following [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML] class diagram captures the scenario we are illustrating:
[[Image:strategy_pattern.jpg]]


ApplicationObject  would be having instance of IcompressStrategy. IcompressStrategy  is the common interface and defines generic algorithmic method which would be extended by various classes which implements the algorithm. Having instance of interface in Applicationobject would make possible for selecting different algorithms interchangeably.
[[Image:Strategy_pattern_az.jpg]]


Based on the  File type, we can instantiate the right kind of Compressor. Here we can also have Factory method which helps in deciding the right kind of subclass of IcompressStrategy to instantiate.
ApplicationObject  would be having an instance of IcompressStrategy. IcompressStrategy  is the common interface and it defines generic algorithmic methods which would be extended by various classes which implement the algorithm. Having instance of the interface in the Applicationobject would make it possible for selecting different algorithms interchangeably.
 
Based on the  File type, we can instantiate the right kind of Compressor. Here we can also have [http://en.wikipedia.org/wiki/Factory_pattern Factory] method which helps in deciding the right subclass of IcompressStrategy to instantiate.


==Implementation of Strategy pattern in Dynamic Object Oriented language==
==Implementation of Strategy pattern in Dynamic Object Oriented language==


Ruby Code which makes use of o-o principle to illustrate strategy pattern
Below is the Ruby Code which makes use of the object-oriented principle to illustrate strategy pattern


<pre>
<pre>
Line 103: Line 110:


</pre>
</pre>
Here is quick overview of how we are implementing,
In the above implementation,
we are defining concreteStrategy in separate modules TextCompressor and ImageCompressor and appropriate module
we are defining two separate modules named TextCompressor and ImageCompressor.  The appropriate module
would be included in context, i.e in CompressContext and appropriate strategy would be used by invoking the method
would be included in the CompressContext. By invoking the module method we would be selecting appropriate strategy.
implemented in the module.
 
 




Ruby Code which makes use of blocks to illustrate strategy pattern
Below is the Ruby Code which makes use of blocks to illustrate strategy pattern:
<pre>
<pre>
class CompressContext
class CompressContext
Line 132: Line 136:


</pre>
</pre>
In the above code, we are making use of closure language feature of Ruby to initialize appropriate strategy in initialize method  
In the above code, we are making use of [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure] feature of Ruby language to initialize appropriate strategy in initialize method  
and invoking the method later.
and invoking this method later.


==Implementation of Strategy pattern in Static Object Oriented language==
==Implementation of Strategy pattern in Static Object Oriented language==


Java Code to demonstrate strategy Pattern implementation  
Java Code to demonstrate strategy pattern implementation  
<pre>
<pre>
// Main Method of Context Class..
// Main Method of Context Class..
Line 164: Line 168:
}
}
</pre>
</pre>
== Comparison of Dynamic and Static o-o language features in implementing Strategy pattern ==
 
== Comparison of Dynamic and Static object-oriented language features in implementing Strategy pattern ==
The following are the key observations noted when we implemented Strategy Pattern in Dynamic and Static object-oriented language:
* For implementing the strategy pattern in a static object-oriented language like Java, we need to define a common interface and the interface must be extended by other classes which implement different algorithm.In the case of dynamic object-oriented language like Ruby,as we have seen in the example [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch3_3h_az#Implementation_of_Strategy_pattern_in_Static_Object_Oriented_language section 3.2], modules can be extended to include strategy methods.There is no need to have a common interface.
* In static object-oriented languages, to implement each algorithm we need to have different interface/strategy which would be extended by different [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch3_3h_az#Components_in_the_implementation_of_a_strategy_pattern ConcreteStrategy] classes.This would result in increasing the code base.Whereas in dynamic object-oriented languages, each module can have different strategies and the context class can include the module and selectively call the appropriate method.
* In both the Static object-oriented and Dynamic object-oriented languages,the design pattern framework can be implemented with equal clarity. But the Java language does not use language idioms, which makes the code easier to understand if one knows object-oriented languages. In Ruby, using blocks and other such language specific constructs might make understanding the code a little more tough.


=Conclusion=
=Conclusion=
 
The dynamic feature of Ruby helps make implementation of Strategy Pattern succinct with the use of blocks and other such language constructs.By using its block construct,one can eliminate the behavioral classes altogether.  The static nature of Java requires it to create a interface and extend it to implement different behaviors. As a result the code is usually longer. The block language construct of Ruby can be used to implement different behaviors at run time, in addition to being included in modules at compile time.This flexibility is allowed by meta-programming.Also,Ruby provides better code re-usability through the use of unbounded polymorphism.


=References=
=References=
# http://www.dofactory.com/Patterns/PatternStrategy.aspx
# http://www.dofactory.com/Patterns/PatternStrategy.aspx
#[http://www.amazon.com/Head-First-Design-Patterns/dp/0596007124 Head First Design Patterns]
#[http://www.amazon.com/Head-First-Design-Patterns/dp/0596007124 Head First Design Patterns]
#[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Pattern Wiki]
#[http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf CSC517 Class notes]
#[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern wiki]
#[http://lists.cs.uiuc.edu/pipermail/gang-of-4-patterns/2003-November/000064.html Differences between Strategy and Bridge Patterns]
#[http://powerdream5.wordpress.com/2007/10/05/the-differences-between-strategy-pattern-and-state-pattern/ Differences between Strategy and State Patterns]
#[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern]
==See Also==
#http://wiki.asp.net/page.aspx/289/strategy/

Latest revision as of 15:24, 15 November 2010

Objective

After reading this Wiki Chapter,the reader should get an overview of

  1. What is a strategy pattern, when and how to use it.
  2. Implementation of strategy pattern in Dynamic and Static object oriented languages.

Introduction

A design pattern is a general reusable solution to a commonly occurring problem in software design3. Strategy Pattern in one such pattern which helps the user to use multiple algorithms interchangeably to reduce multiple conditional statements. This helps in making the code more maintainable.

The intent of Strategy Pattern is to define a family of algorithms,encapsulate each algorithm, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. As an algorithm evolves to handle more and more situations, it can become very complex and difficult to maintain, Strategy pattern can be used to resolve this situation8.

Components in the implementation of a strategy pattern

The components in the implementation of a strategy pattern are1:

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.

When to use Strategy Pattern

  1. Many related classes differ only in their behavior.
  2. You need different variants of an algorithm. For example, defining different algorithms based on space-time tradeoffs.
  3. A class defines many behaviors, and these appear as multiple conditional statements in its operations.Instead, move related conditional branches into their own Strategy class.

Related Patterns

Bridge and State pattern are related patterns to the strategy pattern. Listed below are the key differences6 7-

Strategy Pattern Bridge Pattern State Pattern
The Strategy pattern deals with USING different implementations to implement

different algorithms. Strategy pattern is meant for behavior.

The Bridge pattern deals with HOW you deal with multiple implementations. The Bridge pattern is meant for structure. The State pattern deals with HOW you switch between different states/implementations
It defines a family of algorithms, encapsulate each one and make them interchangeable. It allows an object to alert its behavior when its internal state changes. The object will appear to change its class.The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. It allows an object to alert its behavior when its internal state changes. The object will appear to change its class.
One way to implement the Strategy pattern is to use the Bridge pattern approach or the State pattern approach, but the strategy pattern can also be

implemented a number of other ways.

You cannot use the strategy pattern to implement bridge pattern. You cannot use the strategy pattern to implement state pattern.

Illustration of Strategy pattern through real world example

To illustrate the strategy pattern, let us consider an example of a basic file transfer scenario, where we want to compress the file before transmission. Image files and text files are compressed by using different compression algorithms. Here we would like to demonstrate how this algorithm can be encapsulated in objects and how these objects can be selected without using the conditional statements.

The following UML class diagram captures the scenario we are illustrating:

ApplicationObject would be having an instance of IcompressStrategy. IcompressStrategy is the common interface and it defines generic algorithmic methods which would be extended by various classes which implement the algorithm. Having instance of the interface in the Applicationobject would make it possible for selecting different algorithms interchangeably.

Based on the File type, we can instantiate the right kind of Compressor. Here we can also have Factory method which helps in deciding the right subclass of IcompressStrategy to instantiate.

Implementation of Strategy pattern in Dynamic Object Oriented language

Below is the Ruby Code which makes use of the object-oriented principle to illustrate strategy pattern


class CompressContext
  def initialize(compression_strategy)
    self.class.send :include, compression_strategy
  end
end
 
module TextCompressor
  def compress
     puts 'Compression the text file'
  end
end
 
module ImageCompressor
  def compress
     puts 'Compression the image file'
  end
end
 
class Main
  def self.compressandSend(*args)
    file = args[0]
    
    #=> compressing text file
    compressType = CompressContext.new(TextCompressor)
    compressType.compress    
    
    #=> compressing image file
    compressType = CompressContext.new(ImageCompressor)
    compressType.compress    
 end
  
Main.compressandSend("filepath")
end

In the above implementation, we are defining two separate modules named TextCompressor and ImageCompressor. The appropriate module would be included in the CompressContext. By invoking the module method we would be selecting appropriate strategy.


Below is the Ruby Code which makes use of blocks to illustrate strategy pattern:

class CompressContext
  def initialize(&strategy)
    @strategy = strategy
  end
 
  def compress
    @strategy.call
  end
end

#=> Compress Text File
textCompresser = CompressContext.new { puts 'block which can be used for text compression' }
textCompresser.compress 

#=> Compress Image File
imageCompresser = CompressContext.new { puts 'block which can be used for Image compression' }
imageCompresser.compress 

In the above code, we are making use of closure feature of Ruby language to initialize appropriate strategy in initialize method and invoking this method later.

Implementation of Strategy pattern in Static Object Oriented language

Java Code to demonstrate strategy pattern implementation

// Main Method of Context Class..

 File file = getFile(); //get file path..
 Compresser  ci = CompresserFactory.getCompresser( file.type() );
 ci.performAction();

// implementations:
   interface  Compresser  {
        public void compressAction();
  } 

 class ImageCompressStrategy implements Compresser { 
         public void compressAction() {
             // Use Standard JPEG compress algorithm ....
         }
 }


class TextCompressStrategy implements Compresser { 
         public void compressAction () {
             // use Haufman text compress algorithm.
         }

}

Comparison of Dynamic and Static object-oriented language features in implementing Strategy pattern

The following are the key observations noted when we implemented Strategy Pattern in Dynamic and Static object-oriented language:

  • For implementing the strategy pattern in a static object-oriented language like Java, we need to define a common interface and the interface must be extended by other classes which implement different algorithm.In the case of dynamic object-oriented language like Ruby,as we have seen in the example section 3.2, modules can be extended to include strategy methods.There is no need to have a common interface.
  • In static object-oriented languages, to implement each algorithm we need to have different interface/strategy which would be extended by different ConcreteStrategy classes.This would result in increasing the code base.Whereas in dynamic object-oriented languages, each module can have different strategies and the context class can include the module and selectively call the appropriate method.
  • In both the Static object-oriented and Dynamic object-oriented languages,the design pattern framework can be implemented with equal clarity. But the Java language does not use language idioms, which makes the code easier to understand if one knows object-oriented languages. In Ruby, using blocks and other such language specific constructs might make understanding the code a little more tough.

Conclusion

The dynamic feature of Ruby helps make implementation of Strategy Pattern succinct with the use of blocks and other such language constructs.By using its block construct,one can eliminate the behavioral classes altogether. The static nature of Java requires it to create a interface and extend it to implement different behaviors. As a result the code is usually longer. The block language construct of Ruby can be used to implement different behaviors at run time, in addition to being included in modules at compile time.This flexibility is allowed by meta-programming.Also,Ruby provides better code re-usability through the use of unbounded polymorphism.

References

  1. http://www.dofactory.com/Patterns/PatternStrategy.aspx
  2. Head First Design Patterns
  3. Design Pattern Wiki
  4. CSC517 Class notes
  5. Strategy Pattern wiki
  6. Differences between Strategy and Bridge Patterns
  7. Differences between Strategy and State Patterns
  8. Strategy Pattern

See Also

  1. http://wiki.asp.net/page.aspx/289/strategy/