Javatpoint Logo
Javatpoint Logo

Strategy Pattern

A Strategy Pattern says that "defines a family of functionality, encapsulate each one, and make them interchangeable".

The Strategy Pattern is also known as Policy.


Benefits:

  • It provides a substitute to subclassing.
  • It defines each behavior within its own class, eliminating the need for conditional statements.
  • It makes it easier to extend and incorporate new behavior without changing the application.

Usage:

  • When the multiple classes differ only in their behaviors.e.g. Servlet API.
  • It is used when you need different variations of an algorithm.

Strategy Pattern in (Core Java API's) or JSE 7 API's:

Strategy Pattern

Strategy Pattern in (Advance Java API's) or JEE 7 API's:

Strategy Pattern

UML for Strategy Pattern:

Strategy Pattern

Implementation of Strategy Pattern:

Step 1:

Create a Strategy interface.

Step 2:

Create a Addition class that will implement Startegy interface.

Step 3:

Create a Subtraction class that will implement Startegy interface.

Step 4:

Create a Multiplication class that will implement Startegy interface.

Step 5:

Create a Context class that will ask from Startegy interface to execute the type of strategy.

Step 6:

Create a StartegyPatternDemo class.

Output:

Strategy Pattern





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA