Strategy Pattern

 

Comments

 

Concrete classes of the same interface are created as object and declared as the interface. The object type defines which concrete implementations are used when they are called shortly afterwards.

 

Code

 

 

namespace IVSR.Designpattern.Strategy {
    //The interface for the strategies
    public interface ICalculate {
       int Calculate(int value1, int value2);
    }

    //strategies
    //Strategy 1: Minus
    class Minus : ICalculate {
        public int Calculate(int value1, int value2) {
            return value1 - value2;
        }
    }

    //Strategy 2: Plus
    class Plus : ICalculate {
        public int Calculate(int value1, int value2) {
            return value1 + value2;
        }
    }

    //The client
    class CalculateClient {
        private ICalculate calculateStrategy;

        //Constructor: assigns strategy to interface
        public CalculateClient(ICalculate strategy) {
            this.calculateStrategy = strategy;
        }

        //Executes the strategy
        public int Calculate(int value1, int value2) {
            return calculateStrategy.Calculate(value1, value2);
        }
    }

    //Initialize
    protected void Page_Load(object sender, EventArgs e) {
        CalculateClient minusClient = new CalculateClient(new Minus());
        Response.Write("
Minus: " + minusClient.Calculate(7, 1).ToString()); CalculateClient plusClient = new CalculateClient(new Plus()); Response.Write("
Plus: " + plusClient.Calculate(7, 1).ToString()); } }