Strategy Pattern

1. Identify the aspects of your application that vary and separate them from what stays the same.
2. Always program to an interface and not to an implementation, which means so that objects assigned to those variables  can be of any concrete implementation of the super type, which means the class declaring them doesn’t have to know about the actual object types.

3. Difference between abstract classes and Interfaces
Because Abstract classes are  used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.

An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.
An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.

4. Inheritance is IS-A relationship
In HAS -A relationship or composition, instead of inheriting the behavior, the objects get the behavior by being composed with the right behavior object.

5. Favor composition over in-inheritance
  1. It encapsulates a family of properties into its own set of classes
  2. Lets us change the behavior at run time as long as the object you are composing implements the correct behavior interface

The strategy pattern uses composition instead of inheritance. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at run-time as well as at design-time.


  1. Strategy pattern is useful when we have multiple algorithms for specific task and we want our application to be flexible to chose any of the algorithm at runtime for specific task.
 

 







No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days