Design pattern - GradedJestRisk/method-training GitHub Wiki

Table of Contents

Principles

Identify the aspects of your application that vary, and separate them from what stays the same. => take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary, without affecting those that don't. All patterns provide a way to let some part of a system varies independently of all other parts.

Program to an interface, not an implementation (coming form a super class or sub class doesn't change the fact it's an implementation).

Favor composition (HAS-A) over inheritance (IS-A). Instead of inheriting its behavior, RubberDuck get its behavior by being composed with the behavior object.

Patterns

Strategy

Program to an interface = program to a supertype = the declared type of the variable (ie. quackBehavior) should be a supertype (ie. QuackBehavior), usually an abstract class or in interface, so that the objects assigned to those variables can be of any concrete implementation of the supertype (ie. Squeak), which means the class creating them (ie. Duck) doesn't have to know about the actual object type.

Exploit polymorphism by programming to a supertype, so that the actual runtime object isn't locked into the code.

Other types of objects can reuse these behaviors : we get the benefit of reuse without all the baggage that come along with inheritance.

We can add new behaviors without:

  • modifying any existing behaviors;
  • modifying any class using existing behaviors.
These behavior can have state too: the class doesn't have to contains only methods.

Definition: Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm wary independently from clients that use it.

⚠️ **GitHub.com Fallback** ⚠️