Strategy Design Pattern Tutorial with Java Coding Example | Strategy Pattern Explained
Summary
TLDRIn this episode of Goldman Digest, the focus is on the Strategy Design Pattern, a software design pattern that allows the behavior of an object to change at runtime. The video explains the concept, provides a Java implementation, and discusses its benefits, including adherence to the Open/Closed Principle and the ability to switch algorithms dynamically. Examples like transportation strategies and a navigation app illustrate the pattern's utility. The host encourages viewers to subscribe and engage with the content, promising a follow-up on the Observer Design Pattern in the next installment.
Takeaways
- đ The video introduces the Strategy Design Pattern, explaining its concept and applications.
- đ It discusses where to use the Strategy Design Pattern in projects, highlighting its utility in software development.
- đ» The presenter provides a Java code implementation of the Strategy Design Pattern, demonstrating its practical application.
- đ The video emphasizes the benefits of using the Strategy Design Pattern, such as the ability to change algorithms at runtime.
- đ A real-world example is given to illustrate the Strategy Design Pattern, making it easier to understand its use cases.
- đ The video links to a GitHub repository where viewers can access the code for the Strategy Design Pattern discussed.
- đ The presenter outlines scenarios where the Strategy Design Pattern is particularly useful, such as when multiple algorithms are needed.
- đ ïž The video explains the Open/Closed Principle in the context of the Strategy Design Pattern, emphasizing code maintainability.
- đ The script encourages viewers to engage by subscribing, liking, and sharing the video, and to comment on their experiences with the pattern.
- âïž The video concludes with a teaser for the next video, which will cover the Observer Design Pattern.
Q & A
What is a strategy design pattern?
-A strategy design pattern is a behavioral design pattern that enables an algorithm's behavior to be selected at runtime. It allows the definition of a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
What is the benefit of using the strategy design pattern?
-Using the strategy design pattern allows you to swap algorithms used inside an object at runtime, supports the open/closed principle by being open for extension but closed for modification, isolates the implementation detail of an algorithm from the code that uses it, and can replace inheritance with composition.
How does the strategy design pattern relate to the open/closed principle?
-The strategy design pattern exemplifies the open/closed principle by allowing new functionalities to be added (open for extension) without modifying existing code (closed for modification). This is achieved by adding new algorithm strategies without altering the context or other strategies.
Can you provide a real-world example of the strategy design pattern mentioned in the script?
-Yes, a real-world example given in the script is choosing a mode of transportation to the airport. Depending on factors like budget or time constraints, one might choose between a bus, a cab, or a bicycle, each representing a different strategy.
What is the context class in the strategy design pattern?
-The context class in the strategy design pattern is the driver class that encapsulates the strategy. It maintains a reference to one of the strategy objects and delegates the work to the linked strategy object instead of executing its own algorithms.
How does the strategy design pattern help in maintaining a navigation app as described in the script?
-The strategy design pattern helps in maintaining a navigation app by allowing the app to add new routing algorithms (like car, cyclist, or walking routes) without significantly increasing the complexity of the main class. It does this by delegating the routing logic to strategy objects, keeping the main class clean and manageable.
What is the role of the strategy interface in the strategy design pattern?
-The strategy interface in the strategy design pattern defines a common interface for all supported algorithms. It allows the context to work with all strategies because they are derived from the same interface, enabling the context to switch between different algorithms at runtime.
How can you add a new algorithm to the strategy design pattern without modifying existing code?
-To add a new algorithm without modifying existing code, you create a new class that implements the strategy interface and then instantiate this new strategy class when needed. The context can then use this new strategy object, adhering to the open/closed principle.
What is the difference between strategy pattern and state pattern as mentioned in the script?
-The strategy pattern is about defining a family of algorithms and making them interchangeable, whereas the state pattern allows an object to alter its behavior when its internal state changes. The strategy pattern is used to switch algorithms at runtime, and the state pattern is used to manage state transitions internally.
How does the script demonstrate the strategy design pattern with a calculator example?
-The script demonstrates the strategy design pattern with a calculator example by defining a strategy interface with a calculate method and various strategy implementations for addition, subtraction, multiplication, and division. The calculator context then uses these strategies to perform operations on numbers based on the selected strategy.
Outlines
đ Introduction to Strategy Design Pattern
The video begins with a warm welcome and an introduction to the topic: the Strategy Design Pattern. The host, Goldman Digest, sets the stage by discussing the importance of understanding design patterns, particularly the Strategy pattern. This pattern allows for the definition of a family of algorithms, encapsulated within separate classes, making them interchangeable. The video promises to cover the use cases, Java implementation, and benefits of this pattern. It also encourages viewers to engage by commenting on their understanding of the State Design Pattern from a previous video, with a link provided for those who missed it. The host invites viewers to subscribe to the channel for quality content and ends the introduction with a call to action for likes, shares, and subscriptions.
đĄ Strategy Design Pattern Explained
This paragraph delves into the concept of the Strategy Design Pattern, illustrating how it enables the selection of an algorithm's behavior at runtime. The host explains that the pattern involves encapsulating related algorithms within a 'context' class, allowing the client program to choose the appropriate algorithm or have the context select it automatically. The pattern is exemplified with real-world scenarios, such as choosing transportation to the airport, and a navigation app that evolves to include different route planning strategies for cars, cyclists, and pedestrians. The paragraph emphasizes the pattern's utility in scenarios where algorithm selection needs to be dynamic and the benefits of adhering to the open-closed principle, which promotes extensibility without modifying existing code.
đ Implementation of Strategy Design Pattern
The host transitions into demonstrating the Strategy Design Pattern through a Java code example. The code, available on GitHub, showcases a 'calculator' scenario where different strategies for arithmetic operations (addition, subtraction, etc.) are implemented as separate classes. The 'calculator' class uses a strategy object to perform operations, allowing the operation to be changed at runtime. The video walks through the code, explaining the structure and the strategy interface, followed by concrete strategy classes for each arithmetic operation. The test class is then highlighted, which initializes the calculator with different strategies to perform calculations, demonstrating the flexibility of the pattern in action.
đ Use Cases and Benefits of Strategy Design Pattern
The final paragraph summarizes the Strategy Design Pattern's applications and advantages. The host outlines scenarios where the pattern is particularly useful, such as when an object needs to use different algorithms or when there are many similar classes that differ only in execution. The benefits discussed include the ability to swap algorithms at runtime, adherence to the open-closed principle, isolation of algorithm implementation details, and the replacement of inheritance with composition. The video concludes with a teaser for the next topic, the Observer Design Pattern, and a call to action for viewers to subscribe, like, and share the video for more educational content.
Mindmap
Keywords
đĄStrategy Design Pattern
đĄContext Class
đĄAlgorithm
đĄOpen-Closed Principle
đĄRuntime
đĄEncapsulation
đĄClient Program
đĄInheritance vs Composition
đĄConditional Statements
đĄObserver Design Pattern
Highlights
Introduction to strategy design pattern, its use, and Java code implementation.
The strategy design pattern allows the selection of algorithms at runtime.
Encapsulation of algorithms into separate classes, making their objects interchangeable.
Strategy design pattern consists of multiple related algorithms encapsulated in a context class.
Context class is not responsible for selecting the appropriate algorithm; the client passes the strategy.
Real-world example: Different transportation methods (bus, cab, bicycle) can represent various strategies.
Example of a navigation app that can have multiple route algorithms like car, bike, and walking.
Strategy design pattern prevents code duplication by keeping algorithms in separate classes.
Strategy pattern supports the open-closed principle (code open for extension but closed for modification).
Java code implementation of the strategy pattern with examples of addition, subtraction, multiplication strategies.
Test class demonstrates switching between algorithms (addition, subtraction) at runtime.
Runtime selection of algorithms like addition and subtraction in the calculator example.
Use cases for strategy pattern: when needing to switch algorithms within an object dynamically.
Benefits: Isolating the implementation details of an algorithm from the context and client classes.
Upcoming video on Observer design pattern, with Java implementation and use cases.
Transcripts
[Music]
hello good morning friends welcome back
to your favorite Channel Goldman Digest
today in this video we will discuss what
is strategy design pattern
where to use strategy design pattern in
our project I will also show the Java
code implementation of strategy design
pattern and at the end we will discuss
the benefit of strategy design pattern
so stay tuned till the end of the video
will have lot of exciting discussion on
this
friends in the previous video we
discussed about State design pattern
can you explain what is a state design
pattern and how to use it
please reply your answer in the comment
section
and if you have not seen that previous
video I recommend you to go and see that
video State design pattern is a very
important design pattern you must know
what is a state design pattern
the link of that video is provided on
your screen and also provided in the
description section
just to recall what is a state design
pattern the state design pattern lets an
object alter Its Behavior when its
internal State changes
so for the more information please go
and see previous video friends before we
proceed in this video I want you to
subscribe my channel to grow code one
digest family friends I am creating a
lot of quality contents for you but I'm
not getting subscribers I want you to
like share and subscribe my channel so
that I can grow good one digest family
thank you
[Applause]
okay friends now let's start with
strategy design pattern
what is a strategy design pattern
strategy design pattern lets you define
a family of algorithm put each of them
into a separate class and make their
objects interchangeable
strategy pattern also known as policy
pattern
is a software design pattern that
enables an algorithm Behavior to be
selected at runtime
the strategy pattern consists of number
of related algorithm encapsulated in a
driver class called the context
your client program can select one of
those different algorithms or in some
cases the context might select the best
one for you
the strategy pattern are nothing but an
encapsulation of all those algorithms
inside a context class
this pattern is useful when you want to
decide on runtime which algorithm to be
used
in a strategy pattern we create objects
which represent the various strategies
and a context object whose Behavior
varies as per the strategy is selected
the strategy object changes the
executing algorithm of contacts object
these also example of open close
principle
which make sure that code is open for
extension but close for modification
example if you want to add a new
functionality you can add by adding a
new algorithm
without touching an existing code
right let's understand strategic design
pattern with the real world example
imagine you want to go to airport and
you can catch a bus
order a cab or you can go buy bicycle
these are your transportation strategies
you can pick one of the strategy
depending on your factors such as budget
or time constraints
Etc
let's take another example of strategy
design pattern
let's say you decide to create a
navigation app for a casual Travelers
an important feature for an app was
automatic route planning a user should
be able to enter an address and see the
fastest route to the destination on a
map
the first version of the app build
routes only for the car
then later you plan to add root building
for the cyclist
and in the third release you want to add
option for walking routes
though from business perspective the app
is successful but from technical side it
may be a headache
each time you add a new root algorithm
the main class of Navigator double its
size
at the same point that code become too
hard to maintain problem
so the solution to this problem of
explosion is strategy pattern
the strategy pattern suggests that you
take class that does something specific
and extract all of those algorithm into
a separate classes
called strategies
the original class called context must
have a field for storing a reference to
one of the strategies
the context delegates the work to a
linked strategy object instead of
executing its own
the contact is not responsible for
selecting an appropriate algorithm for a
job instead the client passes the
desired strategy to the context
the context works with all the
strategies because all strategies are
derived from a same interface
in this step you can add new algorithm
or modify existing one without changing
the code of context or other strategies
friends now let me show you an
implementation of strategy design
pattern
I have prepared a code for strategy
design pattern
and I'll walk you through the code first
and then I'll run the code and show you
the demo of strategy design pattern
friends this code is also available in
my GitHub repository you can download
the code and play with it the link of my
GitHub repository shown on your screen
and also available in the description
section of
this video
okay let me show you what I have done in
this strategy design pattern I have a
package strategy where I have all the
class for strategy design pattern
and I have defined
a class strategy so I'm taking an
example of let's say calculator where
I am taking two numbers as an input and
I may have a different strategy of
addition subtraction multiplication or
Division and so on
strategy where I am defining a method
calculate and it just take two numbers
now I can have an implementation
various implementation of this strategy
so one is ADD strategy where I am
implementing that method
for these two numbers I am doing
addition
because it is a add strategy then I am
same way I have a minus strategy
where I am subtracting these two numbers
a minus B
the same way I can have a multiplication
strategy division strategy and so on so
all those strategies we can Define these
are algorithms
now I have a calculator class
where I am taking two numbers as an
input
right and then I am also having a
strategy object here
I am setting that strategy object here
using this method
and finally I have a calculate method
where I have to calculate for these two
number whatever the input numbers are
provided to me I have to perform
operation on this two number in this
calculate method
but in this columnar method I am not
doing direct operation on this number
rather I am calling the calculate matter
of my strategy on these two numbers and
this strategy can change at runtime it
can become addition it can become
subtraction it can become multiplication
or it can become division or and so on
so this is a beauty of a strategy
pattern at runtime you can choose the
algorithm that you want let us see what
and how our test class look like
so in this test class I have defined an
instance of calculator
and I'm initializing those two input
numbers here I am providing these two
numbers as input 10 and 5.
my number one is 10 and number two is
five I am printing it here those two
input numbers then I am also
passing a strategy okay first I want to
perform calculation using addition
strategy so I am setting that additional
strategy and then I am calling
calculator dot calculate
so here when I'm calling calculator dot
calculate internally it will call
calculate method of that strategy
whatever we are passing here so it will
call the calculate method of addition so
it will do the addition of these two
numbers and print the result at this
line
now next time I am changing the strategy
and setting it to minus strategy and
again calling a calculate method then
now the algorithm minus algorithm will
work on the same input and give me the
result and I'll print it here let me run
it and show you that
yeah so my input numbers are 10 and my
input number is 5 so these two are input
so first I am calling the additional
strategy where this two number got added
and second time
I call this SEC minus strategy where
these two number got subtracted to 10
minus 5 is 5. so likewise you can have a
multiple implementation of your
algorithm you can have multiplication
subtraction modulus or and so on in your
project you can decide in your scenario
if you have multiple different
algorithms you can Implement that and
having a common interface so that you
can switch between those algorithm as
runtime so friends
when do you think you can use strategy
design pattern
you can use strategy design pattern when
you want to use different variant of an
algorithm within an object and be able
to switch from one algorithm to another
one at runtime
use strategy pattern when you have lot
of similar classes that only differ in
the way they execute
use the pattern to isolate the business
logic of a class from the implementation
detail of algorithm that may not be as
important in the context of that logic
use the pattern when your classes have a
massive conditional statement that
switches between a different variant of
the same algorithm
so what benefit do you get from a
strategy design pattern
you can swap algorithms used inside an
object at runtime
it supports open close principle that is
your code is open for extension but
close for modification
you can isolate the implementation
detail of an algorithm from the code
that uses it
you can replace inheritance with the
composition
okay friends let me summarize what we
learned in this video we understood what
is strategy design pattern we saw a real
example of strategy design pattern
we also saw Java code implementation of
strategy design pattern
and we also saw the use cases of
strategy design pattern
at the end we discussed the benefits of
strategic design pattern
so let me know if I have already used
this design pattern in any of your
project or seen a scenario where this
pattern can be useful
please reply in the comment section with
your answer
friends in the next video I'll cover
Observer design pattern
we will learn what is Observer design
pattern what is the use of Observer
design pattern and we will also see a
Java code implementation of Observer
design pattern
we'll understand what are the benefits
of Observer design pattern in a project
so stay tuned to the next video comes
and please subscribe to the channel
if you like this video so give it a
thumbs up and subscribe to this channel
for the more interesting videos
click on the Bell icon for the latest
video notifications and do not forget to
share this video with all your friends
and colleagues
this is very useful information for
students beginners and software
engineers
I am putting a lot of efforts in
creating this contents
so please help me growing the code one
digest family
please subscribe to code one digest
channel for the latest programming and
technology related videos
thank you
[Music]
5.0 / 5 (0 votes)