---
# System prepended metadata

title: Head first design pattern easy (Chapter 2)
tags: [OOP, Design pattern]

---

Head first design pattern easy (Chapter 2)
===
###### tags: `OOP` `Design pattern`
1. Observer pattern heavily used in JDK
![](https://i.imgur.com/0LZlMmx.png)

2. Object pattern defines an one to many relationship between a set of objects. When the state of one object changes, all it's dependents are notified, depending the style of notification, the value of observer can also be changed
3. When 2 objects are loosely coupled, they can interact with each other but they have very little knowledge with each other. The observer pattern provides an object design where subject and observers are loosely coupled
4. The subject knows nothing about objects but they implement the Object interface
5. When a new concrete class comes along asking for registration we don't need to modify the subject, we just implement the Object interface to that object and register it
6. We can add/delete observers at runtime
7. We can reuse subject and object because they aren't tightly coupled
8. Strive for loosely coupled design between objects that interact, they minimize the interdependency of each other so they are flexible
9. Observer interface, Observable class, java.util.package
10. In Java Observer pattern support, subject extends the Observable class
11. Implement Observer class and call any of the Observable object.addObserver(), to remove yourself from observer just call deleteobserver
12. Call setChange() to signify that the state has changed
13. Call notifyObservers() or notifyObservers(Object arg) to notify the observers, the Object arg is the arbitrary data that get passed to each observer while being notified
14. update(Observable o, Object arg), the arg is the same object that being passed to notifyObservers, or null if not specified (with args push, without args push)
15. setChange() is used to signify that the state has changed and that notifyObservers shall notify all the observers while being called
16. clearChanged(): change the setted state back to false, hasChanged tells you the current state of Changed flag
17. Never depends on order of evaluation of observer notification, otherwise if observer/observable implementation change then order can be changed, so incorrect result would be produced, this is not loosely coupled
18. You cannot add on observable behaviour to an existing class that has already extended another subclass, which violates OO principle programming to interface not implementation
19. setChanged() method is protected, which means unless you inherit the Observable super class you can't call the method, which violate OO principle: prefer composition over inherit
20. RMI, JavaBeans and Swing also provide implementation of observer pattern