DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Strategy Pattern Example
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Trending

  • Data Quality: A Novel Perspective for 2025
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  • How AI Agents Are Transforming Enterprise Automation Architecture
  1. DZone
  2. Coding
  3. Java
  4. Strategy Pattern Tutorial with Java Examples

Strategy Pattern Tutorial with Java Examples

Learn the Strategy Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Mar. 01, 10 · Tutorial
Likes (23)
Comment
Save
Tweet
Share
403.5K Views

Join the DZone community and get the full member experience.

Join For Free

Having focused on the two factory patterns over the last week, today we'll take a look at the Strategy Pattern, a useful pattern in changing algorithm implementations at runtime, without causing tight coupling.

Strategy in the Real World 

To explain the strategy in the real world, let's take the example of a software developer. If language isn't an issue I might ask a developer to write a piece of code for me to create a user interface. One developer's chosen language is Java, so he'll develop the UI with Swing. Meanwhile, the other developer decides to use C#. I don't mind, I've left the details of how to write the UI to the developers, and both have applied their own strategy. At any stage, the developer chould change their strategy, choosing to use a different language if they feel it's necessary. It's all about dynamically changing behaviours.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Strategy Pattern

The Strategy pattern is known as a behavioural pattern - it's used to manage algorithms, relationships and responsibilities between objects. Thedefinition of Strategy provided in the original Gang of Four book on DesignPatterns states: 

Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour

Now, let's take a look at the diagram definition of the Strategy pattern.

Image title


In the above diagram Context is composed of a Strategy. The context could be anything that would require changing behaviours - a class that provides sorting functionality perhaps. The Strategy is simply implemented as an interface, so that we can swap ConcreteStrategys in and out without effecting our Context.

Let's take a look at how some client might put the Strategy pattern into action: 

 Image title

Use of the Context from the client may vary - your client could tell the Context which strategy it would like to use, or the Context could decide on behalf of the client.  In my opinion, it's better to leave this decision to the Context, as it removes the type switch statements that we saw in our patterns. 

Where Would I Use This Pattern?

The Strategy pattern is to be used where you want to choose the algorithm to use at runtime. A good use of the Strategy pattern would be saving files in different formats, running various sorting algorithms, or file compression.

The Strategy pattern provides a way to define a family of algorithms, encapsulate each one as an object, and make them interchangeable.  

So How Does It Work In Java?

Let's use the example of a file compression tool - where we create either zip or rar files. First we'll need a strategy: 

//Strategy Interface
public interface CompressionStrategy {
  public void compressFiles(ArrayList<File> files);
}

And we'll need to provide our two implementations, one for zip and one for rar

public class ZipCompressionStrategy implements CompressionStrategy {
  public void compressFiles(ArrayList<File> files) {
    //using ZIP approach
  }
}
public class RarCompressionStrategy implements CompressionStrategy {
  public void compressFiles(ArrayList<File> files) {
    //using RAR approach
  }
}

Our context will provide a way for the client to compress the files. Let's say that there is a preferences setting in our application that sets which compression algorithm to use. We can change our strategy using the setCompressionStrategy method in the Context.

public class CompressionContext {
  private CompressionStrategy strategy;
  //this can be set at runtime by the application preferences
  public void setCompressionStrategy(CompressionStrategy strategy) {
    this.strategy = strategy;
  }
  
  //use the strategy
  public void createArchive(ArrayList<File> files) {
    strategy.compressFiles(files);
  }
}

 

It's obvious that all the client has to do now is pass through the files to the CompressionContext

public class Client {
  public static void main(String[] args) {
    CompressionContext ctx = new CompressionContext();
    //we could assume context is already set by preferences
    ctx.setCompressionStrategy(new ZipCompressionStrategy());
    //get a list of files...
    ctx.createArchive(fileList);
  }
} 

Next Up

We've got through 7 of the 23 GoF patterns, so there's still a bit to go in this series. Next we'll be looking at the Visitor pattern, followed the the Proxy pattern.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern
Strategy pattern Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Spring Strategy Pattern Example
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!