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

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

  • AI-Driven RAG Systems: Practical Implementation With LangChain
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • STRIDE: A Guide to Threat Modeling and Secure Implementation
  • Implement a Geographic Distance Calculator Using TypeScript

Trending

  • How Trustworthy Is Big Data?
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Issue and Present Verifiable Credentials With Spring Boot and Android

The Strategy Pattern implemented as an Enum

By 
Alex Theedom user avatar
Alex Theedom
·
Apr. 03, 15 · Interview
Likes (4)
Comment
Save
Tweet
Share
13.6K Views

Join the DZone community and get the full member experience.

Join For Free


What is the Strategy Design Pattern?

The Strategy design pattern is designed to provide a way of selecting from a range of interchangeable strategies.

How is it implemented?

Classic implementation requires that each Strategy implements an interface and provides a concrete implementation for an execute method. The strategy is selected and the execute method called via an interface reference.

Classic implementation of the Strategy Design Pattern

The strategy interface that must be implemented by all strategies.

public interface Strategy {

    public void execute();

}
Two classes showing the implementation of the Strategy interface and a concrete implementation of the execute method.

public class StrategyA implements Strategy {
    @Override
    public void execute(){
        System.out.print("Executing strategy A");
    }
}
public class StrategyB implements Strategy {
    @Override
    public void execute() {
        System.out.print("Executing strategy B");
    }
}
The context class selects the strategy and executes the execute method of the selected strategy.

public class Context {

    private Strategy strategy;

    public void setStrategy(Strategy strategy){
        this.strategy = strategy;
    }

    public void executeStrategy(){
        this.strategy.execute();
    }
}
An example of using the Strategy.

public class UseStrategy {

    public static void main(String[] args){

        Context context = new Context();

        context.setStrategy(new StrategyA());
        context.executeStrategy();

        context.setStrategy(new StrategyB());
        context.executeStrategy();
    }
}


Enum implementation of the Strategy Design Pattern


Now lets look at the above example implemented as an enum. This implementation only requires two classes: an enum class and a class that uses it. All the magic happens in the enum where the concrete implementation of the strategy is done in the definition of each enum constant.

public enum Strategy {

    STRATEGY_A {
        @Override
        void execute(){
            System.out.print("Executing strategy A");
        }
   },

    STRATEGY_B {
    @Override
    void execute(){
        System.out.print("Executing strategy B");
    }
};

    abstract void execute();
}
We use this implementation as follows:

public class UseStrategy {

    public static void main(String[] args){

        UseStrategy useStrategy = new UseStrategy();
        useStrategy.perform(Strategy.STRATEGY_A);
        useStrategy.perform(Strategy.STRATEGY_B);
    }

    private void perform(Strategy strategy){
        strategy.execute();
    }
}


EnumMap implementation of the Strategy design pattern


Alternatively the enum can be selected from a map of Strategies where the key is the enum itself. This is shown in the following example using an EnumMap.

public class EnumMapExample {

static EnumMap lookupStrategy= new EnumMap<>(Strategy.class);

    {
        lookupStrategy.put(Strategy.STRATEGY_A, Strategy.STRATEGY_A);
        lookupStrategy.put(Strategy.STRATEGY_B, Strategy.STRATEGY_B);
    }

    public static void main(String[] args){
        lookupStrategy.get(Strategy.valueOf("STRATEGY_A")).execute();
        lookupStrategy.get(Strategy.valueOf("STRATEGY_B")).execute();
    }
}


Open In Codenvy


To save time you can view this code directly in your browser by using codenvy's cloud IDE. Click this link to view this code now.


Links

  • Git hub repository of this code source
  • Codenvy IDE pre-installed with all the code from this article
 
Strategy pattern Implementation

Opinions expressed by DZone contributors are their own.

Related

  • AI-Driven RAG Systems: Practical Implementation With LangChain
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • STRIDE: A Guide to Threat Modeling and Secure Implementation
  • Implement a Geographic Distance Calculator Using TypeScript

Partner Resources

×

Comments

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: