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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing If-Else Spaghetti: Architecting Cleaner Java with the Strategy Pattern
  • 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

Trending

  • When Production Stops Moving: Running Claude Code Across a Distributed Enterprise Integration Team
  • Every Acquisition Promises One Company. Most Deliver Two.
  • Microsoft Fabric Throttling: Diagnose Before You Scale
  • Catching Query Regressions Before Your Users Do

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

The Strategy Pattern implemented as an Enum

By 
Alex Theedom
·
Apr. 03, 15 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in


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

  • Stop Writing If-Else Spaghetti: Architecting Cleaner Java with the Strategy Pattern
  • 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

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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