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

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Spring Strategy Pattern Example
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • How the Strangler Fig Approach Can Revitalize Complex Applications
  • Design Pattern: What You Need to Know to Improve Your Code Effectively

Trending

  • AWS Fargate: Deploy and Run Web API (.NET Core)
  • Code Complexity in Practice
  • Spring Boot 3.2: Replace Your RestTemplate With RestClient
  • Types of Data Breaches in Today’s World

Strategy Pattern Implemented as an Enum Using Lambdas

Learn how to implement strategy patterns by developing a calculator in Java.

By 
Alex Theedom user avatar
Alex Theedom
·
Jul. 28, 15 · Tutorial
Like (7)
Save
Tweet
Share
21.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this post I would like to show how the strategy pattern can be implemented as an enum with lambdas.

The Strategy Pattern is one of the Gang of Four design patterns published in their book: Elements of Reusable Object-Oriented Software. The intent of the strategy pattern is:

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

We will develop a simple calculator where the strategies are basic arithmetic operations. We start with an interface that defines a single abstract method.

@FunctionalInterface
public interface OperationStrategy {
    T compute(T x, T y);
}


We now implement each arithmetic operation using a lambda expresion.

public enum Operation implements OperationStrategy {

    ADD((x, y) -> x + y),
    SUBTRACT((x, y) -> x - y),
    MULTIPLY((x, y) -> x * y),
    DIVIDE((x, y) -> x / y),
    MAX(Double::max);

    private OperationStrategy operationStrategy;

    Operation(final OperationStrategy operationStrategy) {
        this.operationStrategy = operationStrategy;
    }

    @Override
    public Double compute(Double x, Double y) {
        return operationStrategy.compute(x, y);
    }
}


A series of tests prove that it works.

@RunWith(MockitoJUnitRunner.class)
public class OperationStrategyTest {

    @Test
    public void shouldAddTwoNumbers() {
        assertThat(Operation.ADD.compute(5d, 5d)).isEqualTo(new Double(10));
    }

    @Test
    public void shouldSubtractTwoNumbers() {
        assertThat(Operation.SUBTRACT.compute(10d, 5d)).isEqualTo(new Double(5d));
    }

    @Test
    public void shouldMultiplyTwoNumbers() {
        assertThat(Operation.MULTIPLY.compute(5d, 5d)).isEqualTo(new Double(25));
    }

    @Test
    public void shouldDivideTwoNumbers() {
        assertThat(Operation.DIVIDE.compute(10d, 2d)).isEqualTo(new Double(5d));
    }

    @Test
    public void shouldDetermineMaximumOfTwoNumbers() {
        assertThat(Operation.MAX.compute(10d, 5d)).isEqualTo(new Double(10d));
    }
}


The use of lambdas as strategies reduces boilerplate code quite substantially, though it would not be correct to use lambdas if the strategy is complex and requires a lot of code. It would become cumbersome.

A git repository of this code is available here.

Strategy pattern

Published at DZone with permission of Alex Theedom, 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 the Strangler Fig Approach Can Revitalize Complex Applications
  • Design Pattern: What You Need to Know to Improve Your Code Effectively

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: