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

Related

  • Compliance Automated Standard Solution (COMPASS), Part 10: How OSCAL Mapping Paves the Way for Continuous Compliance Scalability
  • GenAI Implementation Isn't Magic — It’s a Lifecycle
  • The Phantom Write Problem: Why Your Idempotency Implementation Is Silently Losing Data
  • Standards as the Invisible Infrastructure of Software

Trending

  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  • Securing the AI Host: Spring AI MCP Server Communication With API Keys
  • The 7 Pillars of Meeting Design: Transforming Expensive Conversations into Decision Assets

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.9K 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

  • Compliance Automated Standard Solution (COMPASS), Part 10: How OSCAL Mapping Paves the Way for Continuous Compliance Scalability
  • GenAI Implementation Isn't Magic — It’s a Lifecycle
  • The Phantom Write Problem: Why Your Idempotency Implementation Is Silently Losing Data
  • Standards as the Invisible Infrastructure of Software

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook