Skip to content

Latest commit

 

History

History
45 lines (40 loc) · 1015 Bytes

strategy.md

File metadata and controls

45 lines (40 loc) · 1015 Bytes

Strategy

Description

Allowing to change the algorithm/strategy at runtime.

Diagram

Code

Check code here

public interface Discounter {
    double apply(double amount);
}
public class SpringDiscounter implements Discounter {
    @Override
    public double apply(double amount) {
        return amount * 0.9;
    }
}
public class SummerDiscounter implements Discounter {
    @Override
    public double apply(double amount) {
        return amount * 0.8;
    }
}
public class DiscountContext {
    private Discounter discounter;
    public DiscountContext(Discounter discounter) {
        this.discounter = discounter;
    }
    public double apply(double amount) {
        return discounter.apply(amount);
    }
}

To access the instance

final DiscountContext context = new DiscountContext(new SpringDiscounter());
final double amountAfterDiscount = context.apply(100);