SlideShare uma empresa Scribd logo
1 de 43
@alextheedom
Java EE
revisits design patterns
Alex Theedom @alextheedom
@alextheedom
Safe Harbour Statement
All opinions expressed are my own and not endorsed by
any company or entity.
@alextheedom
Who am I?
Alex Theedom, Senior Java Developer
@alextheedom
@alextheedom
Available at
@alextheedom
What’s on?
• Design patterns retrospective
• Map classical design patterns to Java EE 7
• Contexts and Dependency Injection
• Singleton, Factory, Façade, Decorator and Observer
• Final Conclusions
• Q&A
@alextheedom
What are you doing?
• Java Enterprise Edition (J2EE, EE 6/7)
• Spring
@alextheedom
The beginning
•Design Patterns: Elements of Reusable Object-Oriented
Software (E Gamma, R Helm, R Johnson and J Vlissides. 1994)
AKA Gang of Four AKA GoF
•Creational, behavioral and structural
•So what are design patterns in practice?
@alextheedom
Enterprise Java and design
patterns
•JavaOne 2000 talk: Prototyping patterns for the J2EE
platform
•Core J2EE Patterns (D. Anur, J. Crupi and D. Malks)
•Out-of-box design pattern implementations with
Java EE 5
@alextheedom
Java EE Programming Model
•Simplifies programming model
•Annotations have replaced XML description files
•Convention over Configuration
•CDI hides object creation
•Resources are injected by type
•@Inject and disambiguation via custom qualifier
•POJO (JSR 299 managed bean)
•Otherwise @Produces
@alextheedom
Singleton Pattern
•Creational pattern
•Single instance and instantiated once
•Must be thread safe
•Not normally destroy during application life cycle
•Classic implementation: private constructor, double
locking, static initializer, enums …
@alextheedom
Singleton Pattern
@DependsOn("DatabaseConnectionBean")
@Startup
@Singleton
public class Logger {
@PostConstruct
void constructExpensiveObject() {
// Expensive construction
}
}
@DependsOn("DatabaseConnectionBean")
@Startup
@Singleton
public class Logger {
@PostConstruct
void constructExpensiveObject() {
// Expensive construction
}
}
@Inject
Logger logger;
@Inject
Logger logger;
@alextheedom
Singleton Pattern
•Conclusions so far
•Very different implementation
•Substantially less boilerplate code
•Enhancements via specialized annotations
There’s more…
@alextheedom
Singleton Pattern
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Logger {
@AccessTimeout(value = 30, unit=TimeUnit.SECONDS)
@Lock(LockType.WRITE)
public void addMessage(String message) {}
@Lock(LockType.READ)
public String getMessage() {}
}
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Logger {
@AccessTimeout(value = 30, unit=TimeUnit.SECONDS)
@Lock(LockType.WRITE)
public void addMessage(String message) {}
@Lock(LockType.READ)
public String getMessage() {}
}
•Container/bean managed concurrency
@alextheedom
The Good, Bad and the Ugly
•The Good:
•enhancements via specialized annotations
•startup behavioural characteristics
•fine grain control over concurrency and access
timeout
•substantially less boilerplate code
@alextheedom
The Good, Bad and the Ugly
•The Bad:
•overuse can cause problems
•lazy loading causes delays
•eager loading causes memory problems
@alextheedom
•And the ugly:
•considered an anti-pattern
•only niche use
•smarter to use a stateless session bean
The Good, Bad and the Ugly
@alextheedom
Factory Pattern
•Creational pattern
•Interface for creating family of objects
•Clients are decoupled from the creation
@alextheedom
Factory Pattern
•CDI framework is a factory !?!
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
•Use it like so:
@Inject
DrinksMachine drinksMachine;
@Inject
DrinksMachine drinksMachine;
@alextheedom
Factory Pattern
•Problem! Multiple concrete implementations
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
public class SoftDrinksMachine implements DrinksMachine {
// Implementation code
}
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
public class SoftDrinksMachine implements DrinksMachine {
// Implementation code
}
@Inject
DrinksMachine drinksMachine;
@Inject
DrinksMachine drinksMachine;
•Which DrinksMachine to inject?
?!?
@alextheedom
Factory Pattern
•Solution! Qualifiers
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface SoftDrink
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface SoftDrink
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Coffee
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Coffee
@alextheedom
Factory Pattern
•Annotate respective classes
@Coffee
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
@Coffee
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
@SoftDrink
public class SoftDrinksMachine implements DrinksMachine {
// Implementation code
}
@SoftDrink
public class SoftDrinksMachine implements DrinksMachine {
// Implementation code
}
@alextheedom
Factory Pattern
•Annotate injection points
@Inject @SoftDrink
DrinksMachine softDrinksMachine;
@Inject @SoftDrink
DrinksMachine softDrinksMachine;
@Inject @Coffee
DrinksMachine coffeeDrinksMachine;
@Inject @Coffee
DrinksMachine coffeeDrinksMachine;
@alextheedom
Factory Pattern
•Remember
•Only JSR299 beans are ‘injectable’
•But I want to inject a Collection type or Object with a
parameterized constructor
-> let’s dive deeper
@alextheedom
Factory Pattern
•Dive deeper
•Producer methods
•Use it like so:
@History
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@History
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@History
@Inject
List<Books> library;
@History
@Inject
List<Books> library;
@alextheedom
Factory Pattern
•Scope
•Determines when method called
•Life of object: @RequestScoped -> @ApplicationScoped
@RequestScoped
@History
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@RequestScoped
@History
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@alextheedom
The Good, Bad and the Ugly
•The Good:
•easy to implement
•no boilerplate code
•works magically
•any object can be made injectable
•automatic per class configuration
•Disambiguation/filtration via qualifiers
@alextheedom
The Good, Bad and the Ugly
•The Bad: named annotation is not type safe
@Named("History") -> @History
•and the ugly: object creation hidden, hard to follow
execution flow, IDE should help
@alextheedom
Façade Pattern
•Hides the complex logic and provides the interface for
the client
•Typically used in APIs
•Classic implementation: Just create a method to hide
complexity
@alextheedom
Façade Pattern
•Encapsulates complicated logic
•@Stateless, @Stateful
@Stateless
public class BankServiceFacade{
public void complexBusinessLogic(){
// Very very complex logic
}
}
@Stateless
public class BankServiceFacade{
public void complexBusinessLogic(){
// Very very complex logic
}
}
@Inject
public BankServiceFacade service;
@Inject
public BankServiceFacade service;
@alextheedom
The Good, Bad and the Ugly
•The Good: simple, robust, gives you a range of services
•The Bad: over use introduces unnecessary layers, if you
don’t need it don’t introduce one
•and the ugly: there isn’t one really
@alextheedom
Decorator Pattern
•Structural Pattern
•Dynamically adds logic to an object at runtime
•More flexible that inheritance
•Classic implementation: Both the decorator and target
object share the same interface. Decorator wraps the
target object and adds its own behaviour
@alextheedom
Decorator Pattern
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public class PriceDiscountDecorator implements Product {
@Coffee
@Any
@Delegate
@Inject
private Product product;
public String generateLabel() {
product.setPrice(product.getPrice() * 0.5);
return product.generateLabel();
}
}
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public class PriceDiscountDecorator implements Product {
@Coffee
@Any
@Delegate
@Inject
private Product product;
public String generateLabel() {
product.setPrice(product.getPrice() * 0.5);
return product.generateLabel();
}
}
@alextheedom
•The Good: very easy to change behaviour without
breaking legacy code
•The Bad: needs XML config (<CDI 1.1)
•and the ugly: overuse will introduce an execution flow
which is hard to follow
The Good, Bad and the Ugly
@alextheedom
Observer Pattern
•Behavioural Pattern
•Publisher-Subscriber
•Classic implementation: Implement a Subscriber
interface, register with publisher and call a notify
method on subscribers
@alextheedom
Observer Pattern
•Notifies dependents of state change
@Stateless
public class PublishService {
@Inject
Event<String> event;
public void producer(){
event.fire("Take me to your leader");
}
}
@Stateless
public class PublishService {
@Inject
Event<String> event;
public void producer(){
event.fire("Take me to your leader");
}
}
@alextheedom
Observer Pattern
•Dependent receives state change notification
@Stateless
public class MessageObserver {
public void trace(@Observes String message){
System.out.println(message);
}
}
@Stateless
public class MessageObserver {
public void trace(@Observes String message){
System.out.println(message);
}
}
@alextheedom
Observer Pattern
•Qualifier to filter events
@WarningMessage
@Inject
Event<String> event;
@WarningMessage
@Inject
Event<String> event;
public void trace(@Observes @WarningMessage String message)public void trace(@Observes @WarningMessage String message)
@alextheedom
The Good, Bad and the Ugly
•The Good: very easy, no boilerplate code, less than JMS,
the container does the heavy lifting, light weight
•The Bad: confusing execution order but IDE will help
•and the ugly: nothing, its beautiful
@alextheedom
Entity
•Lightweight domain object which is persistable
•Annotated with javax.persistence.Entity
•Can represent relational data object/relational mapping
annotations
@alextheedom
Entity
@Entity
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
}
@Entity
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
}
@alextheedom
Final Conclusion
•Efficiency savings
•Greater control over behaviour
•New features enhance implementation
@alextheedom
Q & A
@alextheedom
Java EE
revisits design patterns
Alex Theedom @alextheedom
Thank you

Mais conteúdo relacionado

Mais procurados

Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldEfficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldMarakana Inc.
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...seleniumconf
 
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldEfficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldMarakana Inc.
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnitWO Community
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperFabrit Global
 
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)Thorben Janssen
 
Coding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerCoding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerMatthew Farwell
 
WebObjects Developer Tools
WebObjects Developer ToolsWebObjects Developer Tools
WebObjects Developer ToolsWO Community
 
Effiziente persistierung
Effiziente persistierungEffiziente persistierung
Effiziente persistierungThorben Janssen
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responsesdarrelmiller71
 
Using Selenium to Improve a Teams Development Cycle
Using Selenium to Improve a Teams Development CycleUsing Selenium to Improve a Teams Development Cycle
Using Selenium to Improve a Teams Development Cycleseleniumconf
 
Automating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on CloudAutomating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on CloudJonghyun Park
 
Drupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHPDrupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHPAntonio Peric-Mazar
 

Mais procurados (19)

Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldEfficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
 
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldEfficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular Developer
 
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
 
Coding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerCoding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checker
 
Web works hol
Web works holWeb works hol
Web works hol
 
WebObjects Developer Tools
WebObjects Developer ToolsWebObjects Developer Tools
WebObjects Developer Tools
 
Effiziente persistierung
Effiziente persistierungEffiziente persistierung
Effiziente persistierung
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responses
 
Using Selenium to Improve a Teams Development Cycle
Using Selenium to Improve a Teams Development CycleUsing Selenium to Improve a Teams Development Cycle
Using Selenium to Improve a Teams Development Cycle
 
Automating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on CloudAutomating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on Cloud
 
Drupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHPDrupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHP
 
Foundation selenium java
Foundation selenium java Foundation selenium java
Foundation selenium java
 

Destaque

Java EE 8: What Servlet 4 and HTTP2 Mean
Java EE 8: What Servlet 4 and HTTP2 MeanJava EE 8: What Servlet 4 and HTTP2 Mean
Java EE 8: What Servlet 4 and HTTP2 MeanAlex Theedom
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)David Delabassee
 
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
Project Avatar (Lyon JUG & Alpes JUG  - March 2014)Project Avatar (Lyon JUG & Alpes JUG  - March 2014)
Project Avatar (Lyon JUG & Alpes JUG - March 2014)David Delabassee
 
GoF J2EE Design Patterns
GoF J2EE Design PatternsGoF J2EE Design Patterns
GoF J2EE Design PatternsThanh Nguyen
 
Jee design patterns- Marek Strejczek - Rule Financial
Jee design patterns- Marek Strejczek - Rule FinancialJee design patterns- Marek Strejczek - Rule Financial
Jee design patterns- Marek Strejczek - Rule FinancialRule_Financial
 
Mobile Java with GWT: Still "Write Once, Run Everywhere"
Mobile Java with GWT: Still "Write Once, Run Everywhere"Mobile Java with GWT: Still "Write Once, Run Everywhere"
Mobile Java with GWT: Still "Write Once, Run Everywhere"Alex Theedom
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE PatternsEmprovise
 
HTTP/2 and Java: Current Status
HTTP/2 and Java: Current StatusHTTP/2 and Java: Current Status
HTTP/2 and Java: Current StatusSimone Bordet
 
J2ee (java ee) design patterns and architecture
J2ee (java ee) design patterns and architectureJ2ee (java ee) design patterns and architecture
J2ee (java ee) design patterns and architectureinTwentyEight Minutes
 
Java days Lviv 2015
Java days Lviv 2015Java days Lviv 2015
Java days Lviv 2015Alex Theedom
 
Jersey Coders New Term Introduction
Jersey Coders New Term IntroductionJersey Coders New Term Introduction
Jersey Coders New Term IntroductionAlex Theedom
 
Java 8 and 9 in Anger
Java 8 and 9 in AngerJava 8 and 9 in Anger
Java 8 and 9 in AngerTrisha Gee
 
HTTP/2 Comes to Java - What Servlet 4.0 Means to You
HTTP/2 Comes to Java - What Servlet 4.0 Means to YouHTTP/2 Comes to Java - What Servlet 4.0 Means to You
HTTP/2 Comes to Java - What Servlet 4.0 Means to YouDavid Delabassee
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Alexander Pashynskiy
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016Alex Theedom
 
Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Edward Burns
 
Java 9 Functionality and Tooling
Java 9 Functionality and ToolingJava 9 Functionality and Tooling
Java 9 Functionality and ToolingTrisha Gee
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsMurat Yener
 
Java EE 8 - February 2017 update
Java EE 8 - February 2017 updateJava EE 8 - February 2017 update
Java EE 8 - February 2017 updateDavid Delabassee
 

Destaque (20)

Java EE 8: What Servlet 4 and HTTP2 Mean
Java EE 8: What Servlet 4 and HTTP2 MeanJava EE 8: What Servlet 4 and HTTP2 Mean
Java EE 8: What Servlet 4 and HTTP2 Mean
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
 
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
Project Avatar (Lyon JUG & Alpes JUG  - March 2014)Project Avatar (Lyon JUG & Alpes JUG  - March 2014)
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
 
GoF J2EE Design Patterns
GoF J2EE Design PatternsGoF J2EE Design Patterns
GoF J2EE Design Patterns
 
Jee design patterns- Marek Strejczek - Rule Financial
Jee design patterns- Marek Strejczek - Rule FinancialJee design patterns- Marek Strejczek - Rule Financial
Jee design patterns- Marek Strejczek - Rule Financial
 
Mobile Java with GWT: Still "Write Once, Run Everywhere"
Mobile Java with GWT: Still "Write Once, Run Everywhere"Mobile Java with GWT: Still "Write Once, Run Everywhere"
Mobile Java with GWT: Still "Write Once, Run Everywhere"
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE Patterns
 
HTTP/2 and Java: Current Status
HTTP/2 and Java: Current StatusHTTP/2 and Java: Current Status
HTTP/2 and Java: Current Status
 
J2ee (java ee) design patterns and architecture
J2ee (java ee) design patterns and architectureJ2ee (java ee) design patterns and architecture
J2ee (java ee) design patterns and architecture
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Java days Lviv 2015
Java days Lviv 2015Java days Lviv 2015
Java days Lviv 2015
 
Jersey Coders New Term Introduction
Jersey Coders New Term IntroductionJersey Coders New Term Introduction
Jersey Coders New Term Introduction
 
Java 8 and 9 in Anger
Java 8 and 9 in AngerJava 8 and 9 in Anger
Java 8 and 9 in Anger
 
HTTP/2 Comes to Java - What Servlet 4.0 Means to You
HTTP/2 Comes to Java - What Servlet 4.0 Means to YouHTTP/2 Comes to Java - What Servlet 4.0 Means to You
HTTP/2 Comes to Java - What Servlet 4.0 Means to You
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016
 
Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015
 
Java 9 Functionality and Tooling
Java 9 Functionality and ToolingJava 9 Functionality and Tooling
Java 9 Functionality and Tooling
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design Patterns
 
Java EE 8 - February 2017 update
Java EE 8 - February 2017 updateJava EE 8 - February 2017 update
Java EE 8 - February 2017 update
 

Semelhante a jDays Sweden 2016

SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"Inhacking
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Derek Jacoby
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure DataTaro L. Saito
 
Using and contributing to the next Guice
Using and contributing to the next GuiceUsing and contributing to the next Guice
Using and contributing to the next GuiceAdrian Cole
 
Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)Mike Schinkel
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with JavascriptAkshay Mathur
 
Hacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeHacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeSean P. Floyd
 
Features, Exportables & You
Features, Exportables & YouFeatures, Exportables & You
Features, Exportables & Youjskulski
 
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMike Croft
 
Clean architecture
Clean architectureClean architecture
Clean architectureLieven Doclo
 
Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsFabian Jakobs
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not JavaChris Adamson
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Doris Chen
 
Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012Lee Klement
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Dutyreedmaniac
 

Semelhante a jDays Sweden 2016 (20)

SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9
 
Agile sites311training
Agile sites311trainingAgile sites311training
Agile sites311training
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure Data
 
Using and contributing to the next Guice
Using and contributing to the next GuiceUsing and contributing to the next Guice
Using and contributing to the next Guice
 
Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with Javascript
 
Hacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeHacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or Runtime
 
Features, Exportables & You
Features, Exportables & YouFeatures, Exportables & You
Features, Exportables & You
 
Protractor survival guide
Protractor survival guideProtractor survival guide
Protractor survival guide
 
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script Applications
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012
 
CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 

Último

Microsoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftMicrosoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftAanSulistiyo
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtrahman018755
 
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceReal Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceEscorts Call Girls
 
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...SUHANI PANDEY
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...SUHANI PANDEY
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdfMatthew Sinclair
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋nirzagarg
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...tanu pandey
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...nirzagarg
 
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...SUHANI PANDEY
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...roncy bisnoi
 
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...SUHANI PANDEY
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)Delhi Call girls
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445ruhi
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...SUHANI PANDEY
 

Último (20)

Microsoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftMicrosoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck Microsoft
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceReal Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
 
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
 
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
 
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 

jDays Sweden 2016

  • 1. @alextheedom Java EE revisits design patterns Alex Theedom @alextheedom
  • 2. @alextheedom Safe Harbour Statement All opinions expressed are my own and not endorsed by any company or entity.
  • 3. @alextheedom Who am I? Alex Theedom, Senior Java Developer @alextheedom
  • 5. @alextheedom What’s on? • Design patterns retrospective • Map classical design patterns to Java EE 7 • Contexts and Dependency Injection • Singleton, Factory, Façade, Decorator and Observer • Final Conclusions • Q&A
  • 6. @alextheedom What are you doing? • Java Enterprise Edition (J2EE, EE 6/7) • Spring
  • 7. @alextheedom The beginning •Design Patterns: Elements of Reusable Object-Oriented Software (E Gamma, R Helm, R Johnson and J Vlissides. 1994) AKA Gang of Four AKA GoF •Creational, behavioral and structural •So what are design patterns in practice?
  • 8. @alextheedom Enterprise Java and design patterns •JavaOne 2000 talk: Prototyping patterns for the J2EE platform •Core J2EE Patterns (D. Anur, J. Crupi and D. Malks) •Out-of-box design pattern implementations with Java EE 5
  • 9. @alextheedom Java EE Programming Model •Simplifies programming model •Annotations have replaced XML description files •Convention over Configuration •CDI hides object creation •Resources are injected by type •@Inject and disambiguation via custom qualifier •POJO (JSR 299 managed bean) •Otherwise @Produces
  • 10. @alextheedom Singleton Pattern •Creational pattern •Single instance and instantiated once •Must be thread safe •Not normally destroy during application life cycle •Classic implementation: private constructor, double locking, static initializer, enums …
  • 11. @alextheedom Singleton Pattern @DependsOn("DatabaseConnectionBean") @Startup @Singleton public class Logger { @PostConstruct void constructExpensiveObject() { // Expensive construction } } @DependsOn("DatabaseConnectionBean") @Startup @Singleton public class Logger { @PostConstruct void constructExpensiveObject() { // Expensive construction } } @Inject Logger logger; @Inject Logger logger;
  • 12. @alextheedom Singleton Pattern •Conclusions so far •Very different implementation •Substantially less boilerplate code •Enhancements via specialized annotations There’s more…
  • 13. @alextheedom Singleton Pattern @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class Logger { @AccessTimeout(value = 30, unit=TimeUnit.SECONDS) @Lock(LockType.WRITE) public void addMessage(String message) {} @Lock(LockType.READ) public String getMessage() {} } @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class Logger { @AccessTimeout(value = 30, unit=TimeUnit.SECONDS) @Lock(LockType.WRITE) public void addMessage(String message) {} @Lock(LockType.READ) public String getMessage() {} } •Container/bean managed concurrency
  • 14. @alextheedom The Good, Bad and the Ugly •The Good: •enhancements via specialized annotations •startup behavioural characteristics •fine grain control over concurrency and access timeout •substantially less boilerplate code
  • 15. @alextheedom The Good, Bad and the Ugly •The Bad: •overuse can cause problems •lazy loading causes delays •eager loading causes memory problems
  • 16. @alextheedom •And the ugly: •considered an anti-pattern •only niche use •smarter to use a stateless session bean The Good, Bad and the Ugly
  • 17. @alextheedom Factory Pattern •Creational pattern •Interface for creating family of objects •Clients are decoupled from the creation
  • 18. @alextheedom Factory Pattern •CDI framework is a factory !?! public class CoffeeMachine implements DrinksMachine { // Implementation code } public class CoffeeMachine implements DrinksMachine { // Implementation code } •Use it like so: @Inject DrinksMachine drinksMachine; @Inject DrinksMachine drinksMachine;
  • 19. @alextheedom Factory Pattern •Problem! Multiple concrete implementations public class CoffeeMachine implements DrinksMachine { // Implementation code } public class SoftDrinksMachine implements DrinksMachine { // Implementation code } public class CoffeeMachine implements DrinksMachine { // Implementation code } public class SoftDrinksMachine implements DrinksMachine { // Implementation code } @Inject DrinksMachine drinksMachine; @Inject DrinksMachine drinksMachine; •Which DrinksMachine to inject? ?!?
  • 20. @alextheedom Factory Pattern •Solution! Qualifiers @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface SoftDrink @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface SoftDrink @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface Coffee @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface Coffee
  • 21. @alextheedom Factory Pattern •Annotate respective classes @Coffee public class CoffeeMachine implements DrinksMachine { // Implementation code } @Coffee public class CoffeeMachine implements DrinksMachine { // Implementation code } @SoftDrink public class SoftDrinksMachine implements DrinksMachine { // Implementation code } @SoftDrink public class SoftDrinksMachine implements DrinksMachine { // Implementation code }
  • 22. @alextheedom Factory Pattern •Annotate injection points @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine;
  • 23. @alextheedom Factory Pattern •Remember •Only JSR299 beans are ‘injectable’ •But I want to inject a Collection type or Object with a parameterized constructor -> let’s dive deeper
  • 24. @alextheedom Factory Pattern •Dive deeper •Producer methods •Use it like so: @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @History @Inject List<Books> library; @History @Inject List<Books> library;
  • 25. @alextheedom Factory Pattern •Scope •Determines when method called •Life of object: @RequestScoped -> @ApplicationScoped @RequestScoped @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @RequestScoped @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; }
  • 26. @alextheedom The Good, Bad and the Ugly •The Good: •easy to implement •no boilerplate code •works magically •any object can be made injectable •automatic per class configuration •Disambiguation/filtration via qualifiers
  • 27. @alextheedom The Good, Bad and the Ugly •The Bad: named annotation is not type safe @Named("History") -> @History •and the ugly: object creation hidden, hard to follow execution flow, IDE should help
  • 28. @alextheedom Façade Pattern •Hides the complex logic and provides the interface for the client •Typically used in APIs •Classic implementation: Just create a method to hide complexity
  • 29. @alextheedom Façade Pattern •Encapsulates complicated logic •@Stateless, @Stateful @Stateless public class BankServiceFacade{ public void complexBusinessLogic(){ // Very very complex logic } } @Stateless public class BankServiceFacade{ public void complexBusinessLogic(){ // Very very complex logic } } @Inject public BankServiceFacade service; @Inject public BankServiceFacade service;
  • 30. @alextheedom The Good, Bad and the Ugly •The Good: simple, robust, gives you a range of services •The Bad: over use introduces unnecessary layers, if you don’t need it don’t introduce one •and the ugly: there isn’t one really
  • 31. @alextheedom Decorator Pattern •Structural Pattern •Dynamically adds logic to an object at runtime •More flexible that inheritance •Classic implementation: Both the decorator and target object share the same interface. Decorator wraps the target object and adds its own behaviour
  • 32. @alextheedom Decorator Pattern @Decorator @Priority(Interceptor.Priority.APPLICATION) public class PriceDiscountDecorator implements Product { @Coffee @Any @Delegate @Inject private Product product; public String generateLabel() { product.setPrice(product.getPrice() * 0.5); return product.generateLabel(); } } @Decorator @Priority(Interceptor.Priority.APPLICATION) public class PriceDiscountDecorator implements Product { @Coffee @Any @Delegate @Inject private Product product; public String generateLabel() { product.setPrice(product.getPrice() * 0.5); return product.generateLabel(); } }
  • 33. @alextheedom •The Good: very easy to change behaviour without breaking legacy code •The Bad: needs XML config (<CDI 1.1) •and the ugly: overuse will introduce an execution flow which is hard to follow The Good, Bad and the Ugly
  • 34. @alextheedom Observer Pattern •Behavioural Pattern •Publisher-Subscriber •Classic implementation: Implement a Subscriber interface, register with publisher and call a notify method on subscribers
  • 35. @alextheedom Observer Pattern •Notifies dependents of state change @Stateless public class PublishService { @Inject Event<String> event; public void producer(){ event.fire("Take me to your leader"); } } @Stateless public class PublishService { @Inject Event<String> event; public void producer(){ event.fire("Take me to your leader"); } }
  • 36. @alextheedom Observer Pattern •Dependent receives state change notification @Stateless public class MessageObserver { public void trace(@Observes String message){ System.out.println(message); } } @Stateless public class MessageObserver { public void trace(@Observes String message){ System.out.println(message); } }
  • 37. @alextheedom Observer Pattern •Qualifier to filter events @WarningMessage @Inject Event<String> event; @WarningMessage @Inject Event<String> event; public void trace(@Observes @WarningMessage String message)public void trace(@Observes @WarningMessage String message)
  • 38. @alextheedom The Good, Bad and the Ugly •The Good: very easy, no boilerplate code, less than JMS, the container does the heavy lifting, light weight •The Bad: confusing execution order but IDE will help •and the ugly: nothing, its beautiful
  • 39. @alextheedom Entity •Lightweight domain object which is persistable •Annotated with javax.persistence.Entity •Can represent relational data object/relational mapping annotations
  • 40. @alextheedom Entity @Entity public class Contact { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; } @Entity public class Contact { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; }
  • 41. @alextheedom Final Conclusion •Efficiency savings •Greater control over behaviour •New features enhance implementation
  • 43. @alextheedom Java EE revisits design patterns Alex Theedom @alextheedom Thank you

Notas do Editor

  1. Introduction: Senior Java Developer, Microservices, background in ATM, middleware, learning systems. Mentor Jersey Coders. Co-author professional Java EE design patterns. Can contact me via email and twitter. I want to hear from you. Any questions or queries.
  2. I wrote a book with Murat Yener, covering in detail the topics I will touch on in this talk. Has anyone bought this book? No OK so here is a discount from Wiley website. Also available at amazon. Also a discount.
  3. The beginning What are design patterns, How did it all start. Long history Construction industry GOF seminal book Cemented world of java Introduces 3 categories: creational, behavioural an structural What are design patterns?  Solutions to problems solved Collective wisdom Avoid reinventing the wheel Overuse Unnecessary use: overcomplicated code, hard to maintain Poor knowledge – hammer What are design patterns?  Solutions to problems solved Collective wisdom Avoid reinventing the wheel Overuse Unnecessary use: overcomplicated code, hard to maintain Poor knowledge – hammer The beginning Did they just appear overnight? Where did they come from? In fact design patterns have a long history starting way before computing, in architecture. That’s the construction type of architecture. But it wasnt really until the GOF wrote their seminal book Design patterns, that the concept of design patterns was cemented in the world of Java. The book introduces a list of design patterns categorised under three titles: creational, behavioural and structural. Design patterns are solutions to problems already solved. They represent the collective wisdom of developers and provide us with a common vocabulary. By implementing solutions that are proven to work we avoid reinventing the wheel and can focus our efforts on solving the other problems we will face as we develop our application. However, we need to take care not to overuse design patterns. Unnecessary use of patterns tends to overcomplicate code making it hard to maintain and a poor design pattern knowledge leads to the inappropriate implementation of patterns to problems that they were not designed to solve. It is very much the case that: If the only tool you have is a hammer, then you will see every problem as a nail. The book&amp;apos;s authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.
  4. After GOF book, JavaOne 2000 talk GOF describes a range of patterns Not all common in Enterprize Java, baked into the API, happened by Java EE 5 After the GOF published their book, there was a talk at Java One 2000 about prototyping patterns for the J2EE platform this talk became a success and the speakers published the talk as a book. The GOF book describes a range of patterns, not all common in Enterprise Java, but those that are common are baked into the APIs of the platform, so instead of having to implement them yourself the platform has them ready to use out of the box. This had already happened by Java EE 5.
  5. Convention over configuration replaces tedious manual configuration DI hides creation and look up of resource Injected as EJB, servlet, singleton, RESTful web service Injected by type, Interfaces confuse container Non-JSR 299 use @Producer The Java EE programming model has been simplified substantially since J2EE. Annotations have replaced the XML description files, convention over configuration have replaced the tedious manual configuration and dependency injection hides the creation and look up of resources. Resources are created and injected at injection points marked by annotations such as @Inject. All you need is a POJO that meets all of the conditions of the managed beans specification JSR 299 and depending on the annotation used it will become an EJB, servlet, singleton or RESTful web service. The object is injected by the container and is determine by type. However using an interface as a type can confuse the container if there is more than one concrete implementation. It doesn’t know which object to inject. This confusion can be resolved by the use of a qualifier annotation that marks the concrete implementation you want to implement. We will see how this annotation is used with @Producer in the implementation of the factory pattern. Beans or objects that you want to inject that do not conform to JSR299 use the @Producer annotation to make them injectable. JSR 299 Managed bean specification It is not a nonstatic inner class. It is a concrete class or is annotated @Decorator. It is not annotated with an EJB component-defining annotation or declared as an EJB bean class in ejb-jar.xml. It has an appropriate constructor. That is, one of the following is the case: The class has a constructor with no parameters. The class declares a constructor annotated @Inject. No special declaration, such as an annotation, is required to define a managed bean.To enable CDI you must have a beans.xml file in your project (under the META-INF or WEB-INF).
  6. Most well know, Spring pool managers and loggers If you read the GOF book Single instance in the JVM Why do we need this? GOF motivation – heavy weight objects If you read further, implementing is quite non-trival Unnatural constructions Java EE elegant and easy OK lets have a look at our first pattern. The singleton pattern is one of the most well known design patterns and is used extensively by frameworks such as Spring, pool mangers and loggers. If you read the GOF book, its about having a single instance of an object in the JVM, that is only ever instantiated once within the life-cycle of the application. Once created it is not normally destroyed until the application terminates. Why do you need this? The GOF motivation was that heavy weight objects, that are expensive, are created by the singleton. If you have read any further in the GOF book, implementing the singleton pattern is quite none trivial. You have to start with some pretty unnatural constructs like private constructors, double locking and the like and in the end you still didn&amp;apos;t get thread safety. You need to think about thread safety as its a single instance being shared across the JVM and across multiple threads.  Java EE offers an elegant and easy way to implement the singleton pattern. 
  7. @Singleton Created container Knows only to create one because @Singleton annotation By default it is read lock and access is serialised So if 2 threads access, forces into serialized access Injection point @PostConstruct Expensive construction part Invoked after construction of the singleton @Startup Default – lazily initialised - first use Start up tasks @startup Not elegant in classical implementation Container will ensure initialised be client requests @Singleton The creation of the singleton class is done by the container and the container knows to create only one instance because the class is annotated with the @Singleton stereotype annotation. By default this object is read locked. Access to it is serialized, so you don&amp;apos;t have to worry about thread safety at all. So if two threads attempt to access the instance they will be forces into serialized access. The container creates an instance of the Logger class and will inject the same instance wherever it finds an injection point. Injection points are annotated @Inject. @PostConstruct Lets get to the expensive construction part. Remember this was one of the principle motivators of the design pattern and why you would want to have the singleton in the first place. We do this by adding the @PostConstruct annotation to the method that constructs the object. This is invoked after construction of the bean singleton itself. @Startup By default the singleton bean is initialized lazily: it wont be created until first use. Normally this is sufficient for most use case scenarios, however you may want the singleton bean to perform application start up tasks in which case you must annotate the bean with @Startup: something that is not elegantly available in the classical implementation of this pattern. The container must ensure that the bean is initialized before it delivers client requests.  @DependsOn The instantiation of your bean may depend on the initialisation of other beans. We can specify the bean on which we depend.
  8. Already we have seen how the Java EE implementation of the singleton pattern is markedly different to its classical implementation and requires substantially less code to achieve the same results. You have been given more control over when the bean is instantiated, either at application start up or on first use, and you can specify its dependency on other beans successful instantiation. These new features enhance the behaviour. And performance of the singleton bean. But we can go further.
  9. Greater control over behaviour Mentioned thread safe by default – container manager @ConcurrentManagement Still need to be careful with method access READ/WRITE @Lock WRITE – locks to other beans READ – allow concurrent access Call to addMessage must wait ConcurrentAccessTimeoutException @AccessTimeout Set wait timeout – class or method Now lets look at how Java EE gives you even greater control over the pattern’s behaviour. Remember that I mentioned that the singleton bean is thread safe by default as concurrency is managed by the container. Well, Java EE offers two types of concurrency management: container managed and bean managed concurrency. By default the container manages the concurrency, removing the need to implement the usual concurrency solutions. @ConcurrentManagement However we are given the option to manage it ourselves by choosing bean managed concurrency. Add the annotation ConcurrencyManagementType.BEAN to the class definition. We still need to be careful with method access as our bean is exposed to a concurrent environment. Two lock types control access to the beans business method: WRITE and READ. @Lock Methods annotated WRITE, lock to other beans while being invoked. Methods that affect change will be annotated this way. Methods annotated READ allow concurrent access. In this code snippet, a call to the getMessage method will be forced to wait until the addMessage method completes. This may result in a ConcurrentAccessTimeoutException if the addMessage() method does not complete within the specified timeout period. @AccessTimeout The timeout period can be configured with an annotation either at the class level or the method level.
  10. Creational logic is encapsulated Provides method for creation Decoupled – does not know different implementations Often implemented as singleton – centralizes creation The factory pattern is a creational design pattern whose intent is to provide an interface for creating families of related or dependent objects without specifying their concrete classes. The creational logic is encapsulated within the factory which either provides a method for its creation  or delegates the creation of the object to a subclass. The client is not aware of the different implementations of the interface or class. The client only needs to know the factory to use to get an instance of one of the implementations of the interface. Clients are decoupled from the creation of the objects.  Often the factory pattern is implemented as a singleton or a static class as only one instance of the factory is required. This centralizes the object creation.
  11. Java EE take advantage of CDI to create objects Not knowing details of their creation Decoupling occurs as result of way IOC implemented by Java EE Most important benefit: decoupling higher-level-classes from lower-level CDI framework is impl. of factory Create object on start up and injects Explain code In Java EE we can take advantage of the CDI framework to create objects without knowing the details of their creation. The decoupling occurs as a result of the way Java EE implements inversion of control. The most important benefit this conveys is the decoupling of higher-level-classes from lower level classes. This decoupling allows the implementation of the concrete class to change without affecting the client: reducing coupling and increasing flexibility. The CDI framework itself is an implementation of the factory pattern. The container creates the qualifying object during application start up and injects it into any injection point that matches the injection criterion. The client does not need to know anything about the concrete implementation of the object, not even the name of the concrete class is known to the client. Here, the container creates an instance of the CoffeeMachine concrete class, it is selected based on its interface DrinksMachine and injected wherever the container finds a qualifying injection point. This is the simplest way to use the CDI implementation of the factory pattern. However its not the most flexible.
  12. More than one implementation Which to inject Fail: ambiguous dependencies How container distinguishes? Java EE gives us qualifiers – custom annotations Annotation class and injection point What happens if we have more than one concrete implementation of the DrinksMachine interface? Which implementation should be injected? SoftDrinksMachine or CoffeeMachine? The container does not know and so deployment will fail with an “ambiguous dependencies” error. So how does the container distinguish between concrete implementations? Java EE gives us a new tool: Qualifiers. Qualifiers are custom annotations that mark the concrete class and the point where you want the container to inject the object. Returning to our Drinks machine and the two concrete classes of the same type CoffeeMachine and SoftDrinksMachine we would distinguish them by the use of two qualifier annotations:
  13. Create qualifiers softdrink, coffee @Target: restricts where use Possible values: TYPE, METOHD, FIELD and PARAMETER We create one qualifier name SoftDrink. This will annotate the SoftDrinksMachine concrete class and Coffee will annotate the CoffeeMachine class. The @Target annotation restricts where we can use these qualifiers to mark injection points, in this case on method and field injection points. The annotation with retention policy RUNTIME ensures that the annotation is available to the JVM through runtime. The possible values for Target are: TYPE, METHOD, FIELD, PARAMETER.
  14. The two concrete implementations of the DrinksMachine interface are annotated appropriately. The CoffeeMachine class is annotated @Coffee while the SoftDrinksMachine class is annotated @SoftDrink.
  15. Annotate injection points Now clear to the container Now you annotate the injection points. Use the qualifier @SoftDrink to denote where you want the container to inject the SoftDrinksMachine class and the qualifier @Coffee where you want the container to inject the CoffeeDrinkMachine. Now we have made it clear to the container where our concrete implementations should be injected and deployment will succeed.
  16. CDI implementation of factory Hides concrete implementations Decouples creation from use Qualifiers select required implementation Remember only injects JSR299 beans Does this mean we cannot take advantage of the CDI framework for none JSR299 No. Java EE provides a solution Lets dive deeper: inject any class of any type. We have seen how Java EE’s CDI framework is an implementation of the factory pattern, how it hides the concrete implementation of an object and allows the creation to be decoupled from its use. We have seen how qualifiers are used to select the required implementation without the need to know anything about the objects creation. It is important to remember that the CDI framework will only instantiate POJOs that meet all of the conditions of the managed beans specification JSR 299. But what if the object you want to inject doesn’t, does that mean we cannot take advantage of the CDI framework’s injection capabilities for classes that don’t comply. No it doesn’t. Java EE provides us with a solution. Lets dive deeper and look at how we can use the CDI framework to inject ANY class of ANY type into an injection point.
  17. Feature call producers Way to instantiate and make available for inject Use to make non-JSR299 compliant objects injectable Producer method produces a list that becomes injectable Producer method creates a list of Book objects Injects into @Library Important scope: default dependent scoped: it inherits the scope of its client Java EE has a feature called producer methods. These methods provide a way to instantiate and therefore make available for injection objects that don’t conform to the managed bean specifications such as objects which require a constructor parameter for proper instantiation. Objects whose value might change at runtime and objects whose creation requires some customised initialization can also be produced ready for injection via a producer method. Lets have a look at a producer method which produces a List populated with Books objects. A list of Book objects will be injected into the injection point annotated @Library. An important feature of the producer method is its scope. This will determine when the method is invoked and for how long the object it produces will live. By default the producer method scope is @DependentScoped. This means that it inherits the scope of its client.
  18. We can extend this example further by giving it a wider scope. If we annotate the producer method @RequestScoped it will be invoked only once for each HTTP request in which it participate, lasting for the duration of the request. Possible scopes are: RequestScoped – HTTP Request ScopeSessionScoped – HTTP Session ScopeApplicationScoped – Shared across usersConversationScoped – Interactions with JSFDependentScoped – Default, inherits from client
  19. 11
  20. 11
  21. What is the facade pattern about? Hides complex logic – interface to client Sound familiar? Abstraction What is special? Why its own name? Create special type of abstraction in Enterprise system You have Application Layer describes part of your subsystem It might perform functions like get orders, list products and matches a given criteria High level API that describes the middle tier of your application to users above that layer level perhaps GUI layer or remote client in simplistic terms, but the underlying code is non-trival. The simple definition is that it hides the complex logic and provides an interface to the client. Sounds familiar? This is nothing much more than the core part of abstraction. One of the core principles of object orientation. So what is special about this and why does it deserve its own name and place in the catalogue of design patterns? Its not merely about creating abstractions but creating a specific type of abstraction in an enterprise system. you will have a layer called the application layer that describes at a higher level what that part of your application/subsystem actually does. Think of this high level use case. That would be describe by a business analysis,: make an order, get a list of products, match given search criteria. High level API that describe the middle tier of your application. That is really want you are doing with the façade, describing these high level abstractions to any user above that layer, perhaps a GUI layer or remote service invocation, they are talking in very simplistic terms to the facade and telling it please do this. The underlining code for that would be non-trival and fairly complex. How do you do this in classic GOF fashion, really not very difficult at all, they are general assumed to be stateless objects often named service or facade and you create essentially atomic method that do a single thing. That is generally how it is implemented in GOF. What does Java EE give you? In this case Java EE has a specialised annotation, the annotation that I talked about before, that is the stateless annotation. It is essentially a marker to denote that this is a facade and that it is intended to be statelesss and to describe atomic operations at the application layer. It can do some very useful things.
  22. @Stateless Inject to use Entirely thread safe – not a singleton Implementation might be using things that are stateful It is entirely thread safe, when you access it, it will be thread safe but it is not a singleton. How it is made thread safe despite not being a singleton, that is beyond the scope of this talk, but essentially it involves some container magic. It is thread safe and stateless, you will never run into thread safety problems, it is by default transactional and it is useful for that tier of your application as you would normally want those high level use cases to be transactional, also it includes things like monitoring management as well as pooling and more importantly defining upper threshold for pool sizes for these services. It is very useful for defining high-level scalable APIs. It is stateless in terms of what the API expectations are. The implementation may be using things that are stateful for example you might have a entity manager that connects to a database. The thread safety is to shield the implementation from any issue with thread safety concerns. Why does it need to be pooled. Very simply, this is essentially the back bone of your application. Lets assume that you have a createorder() method and lets assume that you get a sudden burst of orders and suddenly have 10000 orders to process concurrently, because this object has an implicit upper bound you won&amp;apos;t run into a thread starvation situation. It will only be processed within the upper bounds of that thread pool which is typically 10, 15, 100 threads.
  23. The decorator pattern is one of the GOF Structural Pattern and dynamically adds logic to an object. Instead of inheritance the decorator adds functionality at run time. They introduce a huge amount of flexibility. Classical: Both decorator and target object must implement the same interface. Decorator  wraps the target object and adds its own behaviour. Can be really powerful.
  24. @Decorator @Delegate @Any Add the Decorator annotation to mark the class that will perform the decorating task and the Delegate and Any annotations to the target object. This is where the objects to be decorated will be injected into the decorator class. @Priority Now we defined the order in which this decorator is to be applied. We do this by setting an interpreter priority. Important note: In CDI 1.1 and below the order of the decorators is defined in the bean.xml file. It is the only pattern that requires XML configuration. Now whenever the generateLabel method is called on the target object this method is called first then the call is delegated to the target object&amp;apos;s generateLabel method. @Coffee You can further refine the objects that are subject to decoration by defining any number of qualifiers and the decorator will be bound to only those beans with the same qualifier.
  25. Behavioural pattern. Difficult to understand why it is needed in the first place Fundamental OO – pass a message from one object to another Big difference compared to method invocation: we care about decoupling … A little bit difficult to understand why it is needed in the first place and it goes down to the basic fundamental requirement of OO systems which is to pass a message from one object to another telling the object to do something as a result of a state change on another object but the big difference here verse simply invoking a method on a dependent object is that you care about decoupling in one way or another. Perhaps you have an event for which you want to trigger observers, multiple observers, multiple endpoints that react to that particular endpoint because you want some loose coupling because you want to change which observer actually gets triggered at runtime. This is the original reason you need the observer pattern. The way you implement the observer pattern is sort of antithetical to the original goal of the observer, the GOF way is to implement the interface on a bunch of objects then on the listener you have to register the concrete implementations of each of those instances.  Its a bit self defeating if the goal is to create loosely coupled systems. How does Java EE solve this, it does it in a much more loosely coupled fashion. 
  26. Event In this code snippet we have a stateless bean that is listening for events of type String. When we hear such an event we call event.fire and give it the payload that the observer is expecting. In this case it is a welcome message. All dependents are notified.
  27. The observer has a method with its expected payload which is marked with the Observe annotation, this says: observe for any events that match the payload type of the parameter, in this case a string.
  28. You can also use qualifiers here to filter events. You can qualify the Observes annotation by using the Named annotation or a custom qualifier, when you fire it you can statically provide the qualifier at the event injection point and also in the observer method parameter. By default they are synchronous, however in CDI 2.2 they are introducing asynchronous processing of events. Use case: Image that you have a significant events in your application that you need multiple endpoints to react upon and they are not important enough to put in messaging middle-ware perhaps a system warning. This light-weight approach is perfect for that situation. How about transactions? Events don’t have much to do with transactions, the only place that they interact is that you can have an observer that listens on the transaction so you can get call backs saying that the transaction got committed or rolled back