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.
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.
- The Observable (e.g. weather station) implements the IObservable interface which has
add(IObserver)
,remove(IObserver)
andnotify()
functions. - The Observers (e.g. phone, LCD ... etc.) implements the IObserver interface which has
update()
method. - Instantiate Observable object, doesnt need arguments for Observers.
- Instantiate Observer objects, we need to pass a reference for the Observable (to be able to get data/information)
- Register Observer into the observable using the
add
method. notify
function will be called from within the observable, which will loop through observers and callupdate
.