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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Spring Strategy Pattern Example
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025

Trending

  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Article Moderation: Your Questions, Answered
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  1. DZone
  2. Coding
  3. Java
  4. Strategy Pattern using Lambda Expressions in Java 8

Strategy Pattern using Lambda Expressions in Java 8

By 
Mohamed Sanaulla user avatar
Mohamed Sanaulla
·
Jul. 03, 13 · Interview
Likes (5)
Comment
Save
Tweet
Share
44.7K Views

Join the DZone community and get the full member experience.

Join For Free

Strategy Pattern is one of the patterns from the Design Patterns : Elements of Reusable Object book. The intent of the strategy pattern as stated in the book is:

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

In this post I would like to give an example or two on strategy pattern and then rewrite the same example using lambda expressions to be introduced in Java 8.

Strategy Pattern: An example

Consider an interface declaring the strategy:

interface Strategy{
  public void performTask();
}

Consider two implementations of this strategy:

class LazyStratgey implements Strategy{

  @Override
  public void performTask() {
    System.out.println("Perform task a day before deadline!");
  }
  
}

class ActiveStratgey implements Strategy{

  @Override
  public void performTask() {
    System.out.println("Perform task now!");
  }
  
}

The above strategies are naive and I have kept it simple to help readers grasp it quickly. And lets see these strategies in action:

public class StartegyPatternOldWay {

  public static void main(String[] args) {

    List<Strategy> strategies = 
        Arrays.asList(
          new LazyStratgey(), 
          new ActiveStratgey()
        );
                      
    for(Strategy stg : strategies){
      stg.performTask();
    }
  }
}

The output for the above is:

Perform task a day before deadline!
Perform task now!

Strategy Pattern: An example with Lambda expressions

Lets look at the same example using Lambda expressions. For this we will retain our Strategy interface, but we need not create different implementation of the interface, instead we make use of lambda expressions to create different implementations of the strategy. The below code shows it in action:

import java.util.Arrays;
import java.util.List;

public class StrategyPatternOnSteroids {
  public static void main(String[] args) {
      
    System.out.println("Strategy pattern on Steroids");
    
    List<Strategy> strategies = 
      Arrays.asList(
        () -> {System.out.println("Perform task a day before deadline!");},
        () -> {System.out.println("Perform task now!");}
      );
    
    strategies.forEach((elem) -> elem.performTask());
  }
  
}

The output for the above is:

Strategy pattern on Steroids
Perform task a day before deadline!
Perform task now!

In the example using lambda expression, we avoided the use of class declaration for different strategies implementation and instead made use of the lambda expressions.

Strategy Pattern: Another Example

This example is inspired from Neal Ford’s article on IBM Developer works: Functional Design Pattern-1. The idea of the example is exactly similar, but Neal Ford uses Scala and I am using Java for the same with a few changes in the naming conventions.

Lets look at an interface Computation which also declares a generic type T apart from a method compute which takes in two parameters.

interface Computation<T> {

  public T compute(T n, T m);
}

We can have different implementations of the computation like: IntSum – which returns the sum of two integers, IntDifference – which returns the difference of two integers and IntProduct – which returns the product of two integers.

class IntSum implements Computation<Integer> {

  @Override
  public Integer compute(Integer n, Integer m) {
    return n + m;
  }

}

class IntProduct implements Computation<Integer> {

  @Override
  public Integer compute(Integer n, Integer m) {
    return n * m;
  }
}

class IntDifference implements Computation<Integer> {

  @Override
  public Integer compute(Integer n, Integer m) {
    return n - m;
  }
}

Now lets look at these strategies in action in the below code:

public class AnotherStrategyPattern {

  public static void main(String[] args) {
  
    List<Computation> computations = 
        Arrays.asList(
          new IntSum(), 
          new IntDifference(), 
          new IntProduct()
        );
    
    for (Computation comp : computations) {
      System.out.println(comp.compute(10, 4));
    }
  }
}public class AnotherStrategyPattern {
  public static void main(String[] args) {
  
    List<Computation> computations = 
        Arrays.asList(
          new IntSum(), 
          new IntDifference(), 
          new IntProduct()
        );
    
    for (Computation comp : computations) {
      System.out.println(comp.compute(10, 4));
    }
  }
}

The output for the above is:

14
6
40

Strategy Pattern: Another Example with lambda expressions

Now lets look at the same example using Lambda expressions. As in the previous example as well we need not declare classes for different implementation of the strategy i.e the Computation interface, instead we make use of lambda expressions to achieve the same. Lets look at an example:

public class AnotherStrategyPatternWithLambdas {
  public static void main(String[] args) {

    List<Computation<Integer>> computations = 
          Arrays.asList(
              (n, m)-> { return n+m; },
              (n, m)-> { return n*m; },
              (n, m)-> { return n-m; }
          );
    computations.forEach((comp) -> System.out.println(comp.compute(10, 4)));
  }
}

The output for above is 

14
6
40

From the above examples we can see that using Lambda expressions will help in reducing lot of boilerplate code to achieve more concise code. And with practice one can get used to reading lambda expressions.





Strategy pattern Java (programming language)

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Strategy Pattern Example
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025

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!