Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. # Behavioral pattern
  2.  
  3. ## Strategy
  4.  
  5. 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.
  6.  
  7. ```
  8. @FunctionalInterface
  9. interface BillingStrategy {
  10. // use a price in cents to avoid floating point round-off error
  11. int getActPrice(int rawPrice);
  12. static BillingStrategy normalStrategy() {
  13. return rawPrice -> rawPrice;
  14. }
  15. static BillingStrategy happyHourStrategy() {
  16. return rawPrice -> rawPrice / 2;
  17. }
  18. }
  19.  
  20. class Customer {
  21. private BillingStrategy strategy;
  22.  
  23. public Customer(BillingStrategy strategy) {
  24. this.strategy = strategy;
  25. }
  26. }
  27.  
  28. public class StrategyPattern {
  29. public static void main(String[] arguments) {
  30. // Prepare strategies
  31. BillingStrategy normalStrategy = BillingStrategy.normalStrategy();
  32. BillingStrategy happyHourStrategy = BillingStrategy.happyHourStrategy();
  33.  
  34. Customer firstCustomer = new Customer(normalStrategy);
  35. Customer secondCustomer = new Customer(secondStrategy);
  36. }
  37. }
  38. ```
  39. The idea is to embed runnable functions within the instance (using composition) to change the behavior of the action.
  40.  
  41. ## Observer
  42.  
  43. Push data instead of polling
  44.  
  45. Observable pushes notifications to Observers to let them know that the state has changed
  46. When the Observable changes, the Observers are notified.
  47.  
  48. Defines a one to many dependency between objects, so that one object changes state all of its dependency are notified and updated automatically.
  49.  
  50. 1. The Observable (e.g. weather station) implements the IObservable interface which has `add(IObserver)`, `remove(IObserver)` and `notify()` functions.
  51. 2. The Observers (e.g. phone, LCD ... etc.) implements the IObserver interface which has `update()` method.
  52. 3. Instantiate Observable object, doesnt need arguments for Observers.
  53. 4. Instantiate Observer objects, we need to pass a reference for the Observable (to be able to get data/information)
  54. 5. Register Observer into the observable using the `add` method.
  55. 6. `notify` function will be called from within the observable, which will loop through observers and call `update`.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement