// The strategy interface declares operations common to all
// supported versions of some algorithm. The context uses this
// interface to call the algorithm defined by the concrete
// strategies.
interfaceStrategyismethodexecute(a,b)// Concrete strategies implement the algorithm while following
// the base strategy interface. The interface makes them
// interchangeable in the context.
classConcreteStrategyAddimplementsStrategyismethodexecute(a,b)isreturna+bclassConcreteStrategySubtractimplementsStrategyismethodexecute(a,b)isreturna-bclassConcreteStrategyMultiplyimplementsStrategyismethodexecute(a,b)isreturna*b// The context defines the interface of interest to clients.
classContextis// The context maintains a reference to one of the strategy
// objects. The context doesn't know the concrete class of a
// strategy. It should work with all strategies via the
// strategy interface.
privatestrategy:Strategy// Usually the context accepts a strategy through the
// constructor, and also provides a setter so that the
// strategy can be switched at runtime.
methodsetStrategy(Strategystrategy)isthis.strategy=strategy// The context delegates some work to the strategy object
// instead of implementing multiple versions of the
// algorithm on its own.
methodexecuteStrategy(inta,intb)isreturnstrategy.execute(a,b)// The client code picks a concrete strategy and passes it to
// the context. The client should be aware of the differences
// between strategies in order to make the right choice.
classExampleApplicationismethodmain()isCreatecontextobject.Readfirstnumber.Readlastnumber.Readthedesiredactionfromuserinput.if(action==addition)thencontext.setStrategy(newConcreteStrategyAdd())if(action==subtraction)thencontext.setStrategy(newConcreteStrategySubtract())if(action==multiplication)thencontext.setStrategy(newConcreteStrategyMultiply())result=context.executeStrategy(Firstnumber,Secondnumber)Printresult.