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

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Spring Strategy Pattern Example
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Maven Archetypes: Simplifying Project Template Creation
  • How To Remove Excel Worksheets Using APIs in Java

Trending

  • GenAI: Spring Boot Integration With LocalAI for Code Conversion
  • How To Compare DOCX Documents in Java
  • LLM Orchestrator: The Symphony of AI Services
  • Mastering Serverless Debugging
  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
Like (23)
Save
Tweet
Share
402.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]
  • Maven Archetypes: Simplifying Project Template Creation
  • How To Remove Excel Worksheets Using APIs in Java

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: