Skip to content

Instantly share code, notes, and snippets.

@wael34218
Last active December 16, 2021 16:22
Show Gist options
  • Save wael34218/c5743fdc8ea98767c1f7ff8e18ade94c to your computer and use it in GitHub Desktop.
Save wael34218/c5743fdc8ea98767c1f7ff8e18ade94c to your computer and use it in GitHub Desktop.

Behavioral pattern

Strategy

Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use. It helps reducing the amount of inheritance needed. Instead of creating a multi level convoluted inheritance to share code, you can use Strategy to reduce code complexity and share code across siblings.

@FunctionalInterface
interface BillingStrategy {
    // use a price in cents to avoid floating point round-off error
    int getActPrice(int rawPrice);
    static BillingStrategy normalStrategy() {
        return rawPrice -> rawPrice;
    }
    static BillingStrategy happyHourStrategy() {
        return rawPrice -> rawPrice / 2;
    }
}

class Customer {
    private BillingStrategy strategy;

    public Customer(BillingStrategy strategy) {
        this.strategy = strategy;
    }
}

public class StrategyPattern {
    public static void main(String[] arguments) {
        // Prepare strategies
        BillingStrategy normalStrategy    = BillingStrategy.normalStrategy();
        BillingStrategy happyHourStrategy = BillingStrategy.happyHourStrategy();

        Customer firstCustomer = new Customer(normalStrategy);
        Customer secondCustomer = new Customer(secondStrategy);
    }
}

The idea is to embed runnable functions within the instance (using composition) to change the behavior of the action.

Observer

Push data instead of polling

Observable pushes notifications to Observers to let them know that the state has changed When the Observable changes, the Observers are notified.

Defines a one to many dependency between objects, so that one object changes state all of its dependency are notified and updated automatically.

  1. The Observable (e.g. weather station) implements the IObservable interface which has add(IObserver), remove(IObserver) and notify() functions.
  2. The Observers (e.g. phone, LCD ... etc.) implements the IObserver interface which has update() method.
  3. Instantiate Observable object, doesnt need arguments for Observers.
  4. Instantiate Observer objects, we need to pass a reference for the Observable (to be able to get data/information)
  5. Register Observer into the observable using the add method.
  6. notify function will be called from within the observable, which will loop through observers and call update.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment