Strategy pattern

Strategy pattern

What is the strategy pattern?

Via wikipedia

For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. The validation strategies, encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.


When to use it?

When an object / function may behave differently behavior during the operation of our application. Example: We have the prices of our products but these prices change depending on who buys.

Let’s see how this works on a practical example.


Our strategy interface looks like this:

Now we will take care of calculate the price for our contractors.

For regular customers we give them a 30% discount.

Normal customers buy at the base price.

And for special customers (eg, those we don’t like 🙂 ) we add to the price 30%.

Let’s create price list class.

Our class got information what price calculation adopt and set the base price of the product at 60.

In such a simple way we can now set prices for our customers.

Strategy pattern


It is one of the most commonly used behavior patterns and it’s relatively easy to implement.On the blog i also have a description of patters like : composite , state , observer and command. The rest you will find HERE(PL).

Link to the project.


Leave a Reply

Your email address will not be published. Required fields are marked *