Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Strategy Pattern: Encapsulating Algorithms for Flexible Implementation

Tech Dec 4 4

Overview

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern lets the algorithm vary independently from clients that use it.

Implementation Template

// Abstract algorithm class
abstract class Algorithm {
    // Algorithm method
    public abstract void execute();
}

// Concrete algorithm A
class AlgorithmA extends Algorithm {

    @Override
    public void execute() {
        System.out.println("Algorithm A implementation");
    }
}

// Concrete algorithm B
class AlgorithmB extends Algorithm {

    @Override
    public void execute() {
        System.out.println("Algorithm B implementation");
    }
}

// Concrete algorithm C
class AlgorithmC extends Algorithm {

    @Override
    public void execute() {
        System.out.println("Algorithm C implementation");
    }
}

// Context class
class Context {
    Algorithm algorithm;

    // Initialize with a specific algorithm object
    public Context(Algorithm algorithm) {
        this.algorithm = algorithm;
    }

    // Context interface
    public void performOperation() {
        // Call the algorithm's method based on the specific algorithm object
        algorithm.execute();
    }
}

Strategy Pattern Implementation Example

Consider a pricing system for an e-commerce platform with different strategies: standard pricing, discount offers, and cashback rewards. Since discount offers and cashback rewards represent different algorithms, we can implement the Strategy pattern.

public abstract class PricingStrategy {
    public abstract double calculateTotal(double unitPrice, int quantity);
}

public class StandardPricing extends PricingStrategy {
    @Override
    public double calculateTotal(double unitPrice, int quantity) {
        return unitPrice * quantity;
    }
}

public class DiscountPricing extends PricingStrategy {
    private double discountRate = 1d;

    public DiscountPricing(double discountRate) {
        this.discountRate = discountRate;
    }

    @Override
    public double calculateTotal(double unitPrice, int quantity) {
        return unitPrice * quantity * discountRate;
    }
}

public class CashbackPricing extends PricingStrategy {
    private double thresholdAmount = 0d; // Cashback threshold
    private double cashbackValue = 0d; // Cashback amount

    public CashbackPricing(double thresholdAmount, double cashbackValue) {
        this.thresholdAmount = thresholdAmount;
        this.cashbackValue = cashbackValue;
    }

    @Override
    public double calculateTotal(double unitPrice, int quantity) {
        double total = unitPrice * quantity;
        if (thresholdAmount > 0 && total >= thresholdAmount) {
            total = total - Math.floor(total / thresholdAmount) * cashbackValue;
        }
        return total;
    }
}

The abstract pricing class and three concrete strategies, each implementing the abstract method with different calculation approaches.

public class PricingContext {
    private PricingStrategy pricingStrategy;

    public PricingContext(PricingStrategy pricingStrategy) {
        this.pricingStrategy = pricingStrategy;
    }

    public double getFinalPrice(double unitPrice, int quantity) {
        return pricingStrategy.calculateTotal(unitPrice, quantity);
    }
}

public class ECommerceSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int option = scanner.nextInt();
        PricingContext context = null;

        switch (option) {
            case 1:
                context = new PricingContext(new StandardPricing());
                break;
            case 2:
                context = new PricingContext(new DiscountPricing(0.8));
                break;
            case 3:
                context = new PricingContext(new CashbackPricing(300, 100));
                break;
            default:
                break;
        }
        double finalPrice = context.getFinalPrice(230, 2);
    }
}

The context class and client implementation. The client creates the appropriate pricing strategy based on user selection and delegates it to the context for management. The client code can be further simplified using the Simple Factory pattern.

Combining Strategy Pattern with Simple Factory

Modify the Context class and client code to reduce coupling:

public class PricingContext {
    private PricingStrategy pricingStrategy;

    public PricingContext(int pricingType) {
        switch (pricingType) {
            case 1:
                pricingStrategy = new StandardPricing();
                break;
            case 2:
                pricingStrategy = new DiscountPricing(0.8);
                break;
            case 3:
                pricingStrategy = new CashbackPricing(300, 100);
                break;
            default:
                break;
        }
    }

    public double getFinalPrice(double unitPrice, int quantity) {
        return pricingStrategy.calculateTotal(unitPrice, quantity);
    }
}

public class ECommerceSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int option = scanner.nextInt();
        PricingContext context = new PricingContext(option);
        double finalPrice = context.getFinalPrice(230, 2);
    }
}

Now the client interacts only with the PricingContext class, reducing coupling and improving maintainability.

Summary

  • The Strategy pattern encapsulates different algorithms that perform the same work with different implementations
  • Through an abstract Strategy class, the pattern provides a set of reusable algorithms or behaviors for Context classes, with inheritance extracting common methods
  • The pattern simplifies unit testing as each algorithm has its own class and can be tested independently through its interface
  • The Strategy pattern encapsulates variability, specifically designed to encapsulate algorithms and make them interchangeable

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.