0% found this document useful (0 votes)
19 views24 pages

Se202 Lecture 6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views24 pages

Se202 Lecture 6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

SE202-SOFTWARE DESIGN

AND ARCHITECTURE

LECTURE 6
Strategy Design Pattern
 Concept
 Suppose there is an application where you have multiple algorithms and each of
these algorithms can perform a specific task. A client can dynamically pick any of
these algorithms to serve its current need.
 The strategy pattern suggests that you implement these algorithms in separate
classes. When you encapsulate an algorithm in a separate class, you call it a
strategy. An object that uses the strategy object is often referred to as a context
object. These “algorithms” are also called behaviors in some applications.

 Computer world Example


 Suppose that you have a list of integers and you want to sort them. You do this by
using various algorithms; for example, Bubble Sort, Merge Sort, Quick Sort,
Insertion Sort, and so forth. So, you can have a sorting algorithm with many
different variations. Now you can implement each of these variations (algorithms)
in separate classes and pass the objects of these classes in client code to sort your
integer list.
Strategy Design Pattern
Modes of transportation to an airport is an example of a Strategy. Several options exist,
• driving one's own car,
• taking a taxi,
• an airport shuttle,
• a city bus, or
• a limousine service.
Any of these modes of transportation will get a traveler to the airport, and they can be used
interchangeably.
The traveler must chose the Strategy based on tradeoffs between cost, convenience, and time.

http://sce2.umkc.edu/csee/leeyu/class/CS590L-03/Presentation/Pattern/Strategy.ppt
Strategy Design Pattern
• Strategy
 declares an interface common to all supported algorithms.
 Context uses its interface to call the algorithm defined by a ConcreteStrategy.
• ConcreteStrategy
 implements a specific algorithm using the Strategy interface.
• Context
 is configured with a ConcreteStrategy object.
 maintains a reference to a Strategy object.
 may define an interface for Strategy to use to access its

Java Design Patterns by Rohit Joshi


Example
Example
 I want to design a social media application which allows me to connect to my
friends on all three social platforms i.e. Facebook, Google Plus, Twitter.

 Now I want that client should be able to tell the name of friend and desired
platform – then my application should connect to him transparently.

 More importantly, if I want to add more social platforms into application then
application code should accommodate it without breaking the design.

Which design pattern do you recommend ?

https://howtodoinjava.com/design-patterns/behavioral/strategy-design-pattern/
Solution: Strategy Design Pattern

// connectTo(friendName:String): prints name of the friend and social media platform

Test Program:

// Add your friend «Lokesh» to facebook platform


// Add your friend «Lokesh» to twitter platform
// Add your friend «Lokesh» to googleplus platform

https://howtodoinjava.com/design-patterns/behavioral/strategy-design-pattern/
https://howtodoinjava.com/design-patterns/behavioral/strategy-design-pattern/
https://howtodoinjava.com/design-patterns/behavioral/strategy-design-pattern/
Example
 The class diagram is an example of strategy design pattern but in the
diagram data fields and methods of «Context» class is missing. Complete
the missing parts and implement the following class hierarchy.

Demo Program:
Do following operations
// 10+5
// 10-5
// 10*5

https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
Q: The class diagram is an example of strategy
design pattern but in the diagram data fields
and methods of «Context» class is missing.
Complete the missing parts and implement the
Context class.

https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
Example
 The example will be based on
football.
 Let’s imagine that any football team
can play in two manners: attacking
and defending.
 These two tactics are particular
realisations of a football strategy.

https://www.javacodegeeks.com/2013/06/design-patterns-strategy.html
public class TacticContext { public class Test3 {
private FootballStrategy strategy = null; public static void main(String[] args) {
public void selectTactic(String team) {
strategy.adhereTactic(team); String team1 = "Barcelona";
} String team2 = "Real Madrid";

public FootballStrategy getStrategy() {


TacticContext context = new TacticContext();
return strategy;
}
context.setStrategy(new AttackTactic());
public void setStrategy(FootballStrategy strategy) { context.selectTactic(team1);
this.strategy = strategy;
}
} context.setStrategy(new DefenceTactic());
context.selectTactic(team2);
public interface FootballStrategy { }
public void adhereTactic(String team);
} Output:
}
Barcelona will play in attacking football!
Real Madrid will make emphasis on defence!
public class AttackTactic implements FootballStrategy {
public void adhereTactic(String team) {
System.out.println(team + " will play in attacking football!");
}
}

public class DefenceTactic implements FootballStrategy {


public void adhereTactic(String team) {
System.out.println(team + " will make emphasis on defence!");
}
}
Example
Let us suppose that clients of the EncryptLogger would like to be able to dynamically select and use any of the encryption algorithms.

This requirement can be designed in different ways, including:


• Implementing all algorithms inside the existing encrypt(String) method of the EncryptLogger class using conditional statements
• Applying inheritance, with each subclass of the EncryptLogger implementing a specific encryption algorithm

Though these options look straightforward, applying the Strategy pattern results in a more elegant and efficient design.

Applying the Strategy pattern, each of the encryption algorithms can be encapsulated in a separate (strategy) class. Table 36.4 shows the
list of these strategy classes and the algorithms they implement.
Let us define a common interface to be implemented by each of the strategy classes, in the form of a Java interface EncryptionStrategy, as
follows:
Only the last

public String substring(int startIndex, int endIndex)


startIndex=Inclusive, endIndex=Exclusive
The java string toCharArray() method
converts this string into character array. It
returns a newly created character array, its
length is similar to this string and its
contents are initialized with the characters
of this string.

String(char[] value)
Allocates a new String so that it represents
the sequence of characters currently
contained in the character array argument.
The HashMap class has many useful methods. For example,
 To add items to it, use the put() method.
 To access a value in the HashMap, use the get() method and refer to its
key
 Ex: capitalCities.get("England");
When the EncryptLogger is first instantiated, its current
encryption strategy is set to SimpleEncryption inside its
constructor.

In the new design, the EncryptLogger (the context) is not


affected when changes such as adding, changing or
removing an algorithm are made.
In addition, making such changes will be simpler as each
algorithm is contained in a separate class.

Note: The EncryptLogger contains an object reference of FileLogger type. This relationship is not included in the class diagram as it is
not part of the pattern implementation.
References
 Java Design Patterns, A Hands-On Experience with Real-World Examples, Vaskaran Sarcar
 Software Architecture Design Patterns in Java, Partha Kuchana
Additional Material
Class StringTokenizer
 The string tokenizer class allows an application to break a string into tokens.

 The following is one example of the use of the tokenizer. The code:

StringTokenizer st = new StringTokenizer("this is a test");


while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

 prints the following output:


this
is
a
test

You might also like