Strategy Design Pattern Tutorial with Java Coding Example | Strategy Pattern Explained

Software Design Patterns & Design Principles for Object Oriented Programming & Microservices | Solid Design Principles | Microservice Design Patterns
24 Jan 202313:34

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

00:00

🔑 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.

05:00

💡 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.

10:02

🛠 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

A software design pattern that allows you to define a family of algorithms, encapsulate each one in a separate class, and make their objects interchangeable. It relates to the video's theme as the central topic being discussed, where different algorithms can be selected at runtime depending on the scenario. The presenter explains this pattern with examples of transportation choices and a navigation app that needs to adapt its route planning for cars, cyclists, and walkers.

💡Context Class

In the Strategy Design Pattern, the context class is responsible for interacting with the strategy (algorithm). It holds a reference to a specific strategy object and delegates the execution to that object. In the video, the context class was discussed as the 'calculator' class, which holds input numbers and applies a selected strategy like addition or subtraction.

💡Algorithm

An algorithm is a step-by-step procedure used for calculations, data processing, or automated reasoning tasks. In the Strategy Design Pattern, each strategy encapsulates a different algorithm. The video gives the example of algorithms such as addition, subtraction, multiplication, or division that can be selected at runtime based on the context class's input.

💡Open-Closed Principle

A design principle that states software entities should be open for extension but closed for modification. This principle is linked to the Strategy Design Pattern as the presenter explains that new algorithms can be added without modifying existing code, allowing for flexibility in extending functionality without disrupting the original design.

💡Runtime

The period when a program is executing. In the context of the Strategy Design Pattern, the choice of algorithm can be made at runtime, allowing dynamic behavior based on the circumstances. The presenter emphasizes how this flexibility is one of the main benefits of the strategy pattern, such as selecting addition or subtraction strategies when the program is already running.

💡Encapsulation

Encapsulation in software design involves bundling data with methods that operate on the data. In the Strategy Design Pattern, algorithms are encapsulated within their respective strategy classes. The video mentions encapsulating multiple strategies within the 'calculator' class, making each strategy interchangeable and independent from others.

💡Client Program

A client program is an application that interacts with a service or another piece of software. In the Strategy Design Pattern, the client program decides which strategy (algorithm) to use at runtime. The presenter refers to the 'calculator' example, where the client program chooses whether to perform addition or subtraction.

💡Inheritance vs Composition

Inheritance is a mechanism where one class inherits the properties and behaviors of another. Composition is a design principle where objects are composed of other objects. In the Strategy Design Pattern, composition is favored because it allows algorithms to be easily interchanged without modifying the underlying classes. The presenter contrasts inheritance with the flexibility of composition, as seen in the 'calculator' class that can swap strategies at runtime.

💡Conditional Statements

A conditional statement is used in programming to make decisions based on certain conditions. In the video, the presenter discusses how using the Strategy Design Pattern can reduce the need for massive conditional statements, as different algorithms (strategies) are encapsulated in their own classes, making the code more maintainable.

💡Observer Design Pattern

The Observer Design Pattern allows an object (subject) to notify multiple observers of any state changes automatically. Although briefly mentioned, this design pattern will be covered in the next video, where it will be compared to the Strategy Design Pattern. The presenter teases this pattern as another important design principle that is widely used in software development.

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

play00:00

[Music]

play00:02

hello good morning friends welcome back

play00:05

to your favorite Channel Goldman Digest

play00:06

today in this video we will discuss what

play00:09

is strategy design pattern

play00:11

where to use strategy design pattern in

play00:13

our project I will also show the Java

play00:16

code implementation of strategy design

play00:17

pattern and at the end we will discuss

play00:20

the benefit of strategy design pattern

play00:22

so stay tuned till the end of the video

play00:25

will have lot of exciting discussion on

play00:27

this

play00:28

friends in the previous video we

play00:30

discussed about State design pattern

play00:33

can you explain what is a state design

play00:35

pattern and how to use it

play00:38

please reply your answer in the comment

play00:40

section

play00:41

and if you have not seen that previous

play00:43

video I recommend you to go and see that

play00:46

video State design pattern is a very

play00:48

important design pattern you must know

play00:50

what is a state design pattern

play00:52

the link of that video is provided on

play00:55

your screen and also provided in the

play00:58

description section

play01:00

just to recall what is a state design

play01:02

pattern the state design pattern lets an

play01:05

object alter Its Behavior when its

play01:08

internal State changes

play01:11

so for the more information please go

play01:13

and see previous video friends before we

play01:16

proceed in this video I want you to

play01:18

subscribe my channel to grow code one

play01:21

digest family friends I am creating a

play01:23

lot of quality contents for you but I'm

play01:25

not getting subscribers I want you to

play01:28

like share and subscribe my channel so

play01:31

that I can grow good one digest family

play01:33

thank you

play01:34

[Applause]

play01:38

okay friends now let's start with

play01:40

strategy design pattern

play01:42

what is a strategy design pattern

play01:45

strategy design pattern lets you define

play01:48

a family of algorithm put each of them

play01:51

into a separate class and make their

play01:54

objects interchangeable

play01:56

strategy pattern also known as policy

play01:59

pattern

play02:00

is a software design pattern that

play02:02

enables an algorithm Behavior to be

play02:05

selected at runtime

play02:08

the strategy pattern consists of number

play02:10

of related algorithm encapsulated in a

play02:13

driver class called the context

play02:17

your client program can select one of

play02:19

those different algorithms or in some

play02:24

cases the context might select the best

play02:27

one for you

play02:29

the strategy pattern are nothing but an

play02:31

encapsulation of all those algorithms

play02:33

inside a context class

play02:37

this pattern is useful when you want to

play02:40

decide on runtime which algorithm to be

play02:43

used

play02:45

in a strategy pattern we create objects

play02:47

which represent the various strategies

play02:50

and a context object whose Behavior

play02:53

varies as per the strategy is selected

play02:57

the strategy object changes the

play02:59

executing algorithm of contacts object

play03:03

these also example of open close

play03:06

principle

play03:07

which make sure that code is open for

play03:10

extension but close for modification

play03:14

example if you want to add a new

play03:16

functionality you can add by adding a

play03:18

new algorithm

play03:19

without touching an existing code

play03:22

right let's understand strategic design

play03:25

pattern with the real world example

play03:28

imagine you want to go to airport and

play03:32

you can catch a bus

play03:34

order a cab or you can go buy bicycle

play03:38

these are your transportation strategies

play03:42

you can pick one of the strategy

play03:43

depending on your factors such as budget

play03:46

or time constraints

play03:48

Etc

play03:51

let's take another example of strategy

play03:54

design pattern

play03:55

let's say you decide to create a

play03:57

navigation app for a casual Travelers

play04:00

an important feature for an app was

play04:03

automatic route planning a user should

play04:06

be able to enter an address and see the

play04:08

fastest route to the destination on a

play04:11

map

play04:13

the first version of the app build

play04:15

routes only for the car

play04:17

then later you plan to add root building

play04:21

for the cyclist

play04:22

and in the third release you want to add

play04:25

option for walking routes

play04:28

though from business perspective the app

play04:31

is successful but from technical side it

play04:35

may be a headache

play04:36

each time you add a new root algorithm

play04:39

the main class of Navigator double its

play04:42

size

play04:44

at the same point that code become too

play04:47

hard to maintain problem

play04:49

so the solution to this problem of

play04:51

explosion is strategy pattern

play04:55

the strategy pattern suggests that you

play04:57

take class that does something specific

play05:00

and extract all of those algorithm into

play05:02

a separate classes

play05:04

called strategies

play05:07

the original class called context must

play05:10

have a field for storing a reference to

play05:12

one of the strategies

play05:14

the context delegates the work to a

play05:17

linked strategy object instead of

play05:19

executing its own

play05:22

the contact is not responsible for

play05:24

selecting an appropriate algorithm for a

play05:27

job instead the client passes the

play05:29

desired strategy to the context

play05:32

the context works with all the

play05:34

strategies because all strategies are

play05:36

derived from a same interface

play05:38

in this step you can add new algorithm

play05:41

or modify existing one without changing

play05:44

the code of context or other strategies

play05:48

friends now let me show you an

play05:50

implementation of strategy design

play05:52

pattern

play05:55

I have prepared a code for strategy

play05:57

design pattern

play05:58

and I'll walk you through the code first

play06:00

and then I'll run the code and show you

play06:02

the demo of strategy design pattern

play06:05

friends this code is also available in

play06:08

my GitHub repository you can download

play06:10

the code and play with it the link of my

play06:13

GitHub repository shown on your screen

play06:15

and also available in the description

play06:17

section of

play06:18

this video

play06:20

okay let me show you what I have done in

play06:22

this strategy design pattern I have a

play06:25

package strategy where I have all the

play06:26

class for strategy design pattern

play06:29

and I have defined

play06:31

a class strategy so I'm taking an

play06:34

example of let's say calculator where

play06:37

I am taking two numbers as an input and

play06:40

I may have a different strategy of

play06:42

addition subtraction multiplication or

play06:46

Division and so on

play06:49

strategy where I am defining a method

play06:52

calculate and it just take two numbers

play06:55

now I can have an implementation

play06:58

various implementation of this strategy

play07:01

so one is ADD strategy where I am

play07:04

implementing that method

play07:07

for these two numbers I am doing

play07:09

addition

play07:10

because it is a add strategy then I am

play07:13

same way I have a minus strategy

play07:16

where I am subtracting these two numbers

play07:19

a minus B

play07:20

the same way I can have a multiplication

play07:22

strategy division strategy and so on so

play07:26

all those strategies we can Define these

play07:28

are algorithms

play07:30

now I have a calculator class

play07:34

where I am taking two numbers as an

play07:38

input

play07:39

right and then I am also having a

play07:43

strategy object here

play07:47

I am setting that strategy object here

play07:50

using this method

play07:52

and finally I have a calculate method

play07:54

where I have to calculate for these two

play07:57

number whatever the input numbers are

play08:00

provided to me I have to perform

play08:02

operation on this two number in this

play08:04

calculate method

play08:06

but in this columnar method I am not

play08:09

doing direct operation on this number

play08:10

rather I am calling the calculate matter

play08:13

of my strategy on these two numbers and

play08:16

this strategy can change at runtime it

play08:19

can become addition it can become

play08:21

subtraction it can become multiplication

play08:24

or it can become division or and so on

play08:27

so this is a beauty of a strategy

play08:30

pattern at runtime you can choose the

play08:33

algorithm that you want let us see what

play08:35

and how our test class look like

play08:38

so in this test class I have defined an

play08:40

instance of calculator

play08:43

and I'm initializing those two input

play08:45

numbers here I am providing these two

play08:47

numbers as input 10 and 5.

play08:50

my number one is 10 and number two is

play08:52

five I am printing it here those two

play08:55

input numbers then I am also

play08:59

passing a strategy okay first I want to

play09:04

perform calculation using addition

play09:06

strategy so I am setting that additional

play09:08

strategy and then I am calling

play09:10

calculator dot calculate

play09:12

so here when I'm calling calculator dot

play09:14

calculate internally it will call

play09:15

calculate method of that strategy

play09:17

whatever we are passing here so it will

play09:20

call the calculate method of addition so

play09:22

it will do the addition of these two

play09:25

numbers and print the result at this

play09:27

line

play09:28

now next time I am changing the strategy

play09:31

and setting it to minus strategy and

play09:34

again calling a calculate method then

play09:36

now the algorithm minus algorithm will

play09:39

work on the same input and give me the

play09:42

result and I'll print it here let me run

play09:45

it and show you that

play09:52

yeah so my input numbers are 10 and my

play09:56

input number is 5 so these two are input

play10:00

so first I am calling the additional

play10:01

strategy where this two number got added

play10:04

and second time

play10:05

I call this SEC minus strategy where

play10:08

these two number got subtracted to 10

play10:10

minus 5 is 5. so likewise you can have a

play10:14

multiple implementation of your

play10:16

algorithm you can have multiplication

play10:19

subtraction modulus or and so on in your

play10:24

project you can decide in your scenario

play10:26

if you have multiple different

play10:29

algorithms you can Implement that and

play10:32

having a common interface so that you

play10:34

can switch between those algorithm as

play10:36

runtime so friends

play10:39

when do you think you can use strategy

play10:42

design pattern

play10:44

you can use strategy design pattern when

play10:46

you want to use different variant of an

play10:48

algorithm within an object and be able

play10:52

to switch from one algorithm to another

play10:54

one at runtime

play10:56

use strategy pattern when you have lot

play10:59

of similar classes that only differ in

play11:02

the way they execute

play11:06

use the pattern to isolate the business

play11:08

logic of a class from the implementation

play11:10

detail of algorithm that may not be as

play11:14

important in the context of that logic

play11:16

use the pattern when your classes have a

play11:20

massive conditional statement that

play11:22

switches between a different variant of

play11:23

the same algorithm

play11:25

so what benefit do you get from a

play11:27

strategy design pattern

play11:29

you can swap algorithms used inside an

play11:32

object at runtime

play11:34

it supports open close principle that is

play11:38

your code is open for extension but

play11:40

close for modification

play11:43

you can isolate the implementation

play11:45

detail of an algorithm from the code

play11:47

that uses it

play11:50

you can replace inheritance with the

play11:52

composition

play11:53

okay friends let me summarize what we

play11:56

learned in this video we understood what

play11:58

is strategy design pattern we saw a real

play12:01

example of strategy design pattern

play12:04

we also saw Java code implementation of

play12:06

strategy design pattern

play12:08

and we also saw the use cases of

play12:12

strategy design pattern

play12:13

at the end we discussed the benefits of

play12:16

strategic design pattern

play12:17

so let me know if I have already used

play12:20

this design pattern in any of your

play12:22

project or seen a scenario where this

play12:24

pattern can be useful

play12:26

please reply in the comment section with

play12:28

your answer

play12:29

friends in the next video I'll cover

play12:32

Observer design pattern

play12:35

we will learn what is Observer design

play12:37

pattern what is the use of Observer

play12:39

design pattern and we will also see a

play12:41

Java code implementation of Observer

play12:43

design pattern

play12:44

we'll understand what are the benefits

play12:47

of Observer design pattern in a project

play12:49

so stay tuned to the next video comes

play12:51

and please subscribe to the channel

play12:54

if you like this video so give it a

play12:57

thumbs up and subscribe to this channel

play13:00

for the more interesting videos

play13:02

click on the Bell icon for the latest

play13:04

video notifications and do not forget to

play13:07

share this video with all your friends

play13:09

and colleagues

play13:11

this is very useful information for

play13:13

students beginners and software

play13:15

engineers

play13:16

I am putting a lot of efforts in

play13:18

creating this contents

play13:20

so please help me growing the code one

play13:22

digest family

play13:24

please subscribe to code one digest

play13:26

channel for the latest programming and

play13:28

technology related videos

play13:30

thank you

play13:31

[Music]

Rate This

5.0 / 5 (0 votes)

相关标签
Strategy PatternJava TutorialDesign PatternsSoftware DevelopmentProgramming GuideAlgorithm SelectionOOP PrinciplesCode ExamplesSoftware EngineersObserver Pattern
您是否需要英文摘要?