Java Reference
In-Depth Information
Here we introduce a second argument to the method processCustomer of type
Consumer<Customer> because it matches the signature of the method makeCustomerHappy
defined earlier:
public void processCustomer(int id, Consumer<Customer> makeCustomerHappy){
Customer c = Database.getCustomerWithId(id);
makeCustomerHappy.accept(c);
}
You can now plug in different behaviors directly without subclassing the OnlineBanking class by
passing lambda expressions:
new OnlineBankingLambda().processCustomer(1337, (Customer c) ->
System.out.println("Hello " + c.getName());
This is another example of how lambda expressions can help you remove the boilerplate
inherent to design patterns!
8.2.3. Observer
The observer design pattern is a common solution when an object (called the subject ) needs to
automatically notify a list of other objects (called observers ) when some event happens (for
example, a state change). You typically come across this pattern when working with GUI
applications. You register a set of observers on a GUI component such as button. If the button is
clicked, the observers are notified and can execute a specific action. But the observer pattern
isn't limited to GUIs. For example, the observer design pattern is also suitable in a situation
where several traders (observers) may wish to react to the change of price of a stock (subject).
Figure 8.2 illustrates the UML diagram of the observer pattern.
Figure 8.2. The observer design pattern
Let's write some code to see how the observer pattern is useful in practice. You'll design and
implement a customized notification system for an application like Twitter. The concept is
simple: several newspaper agencies ( NY Times , The Guardian , and Le Monde ) are subscribed to
 
Search WWH ::




Custom Search