Behavioural Design Pattern: Strategy Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Behavioural Design Pattern: Strategy Pattern

Share This
The statement "defines a family of functionality, encapsulates each one, and makes them interchangeable" describes a Strategy Pattern.

The alternative name for the Strategy Pattern is Policy.

The benefits are:
  • It runs concurrently with subclassification. 
  • By defining each behavior in its own class, conditional statements are unnecessary. 
  • It facilitates the incorporation and extension of novel behavior without requiring an application redesign.

The usages are:
  • When the only distinction between multiple classes is their behavior, such as Servlet API. 
  •  It is utilized when various iterations of an algorithm are required.

Source code of ArithmaticAlgorithm.java
package com.t4b.test.java.dp.bp.sp; interface ArithmaticAlgorithm { public int calculate(int num1, int num2); }
Source code of ArithmaticContext.java
package com.t4b.test.java.dp.bp.sp; class ArithmaticContext { private ArithmaticAlgorithm algorithm; public ArithmaticContext(ArithmaticAlgorithm strategy) { this.algorithm = strategy; } public int execute(int num1, int num2) { return algorithm.calculate(num1, num2); } }
Source code of ArithmaticAdd.java
package com.t4b.test.java.dp.bp.sp; class ArithmaticAdd implements ArithmaticAlgorithm { @Override public int calculate(int num1, int num2) { return num1 + num2; } }
Source code of ArithmaticMul.java
package com.t4b.test.java.dp.bp.sp; class ArithmaticMul implements ArithmaticAlgorithm { @Override public int calculate(int num1, int num2) { return num1 * num2; } }
Source code of ArithmaticSub.java
package com.t4b.test.java.dp.bp.sp; class ArithmaticSub implements ArithmaticAlgorithm { @Override public int calculate(int num1, int num2) { return num1 - num2; } }
Source code of TestMain.java
package com.t4b.test.java.dp.bp.sp; public class TestMain { public static void main(String[] args) { int x = 10, y = 5; ArithmaticContext context = new ArithmaticContext(new ArithmaticAdd()); System.out.println(x + " + " + y + " = " + context.execute(x, y)); context = new ArithmaticContext(new ArithmaticSub()); System.out.println(x + " - " + y + " = " + context.execute(x, y)); context = new ArithmaticContext(new ArithmaticMul()); System.out.println(x + " * " + y + " = " + context.execute(x, y)); } }

Happy Exploring!

No comments:

Post a Comment