SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Java EE
revisits design patterns
Alex Theedom @alextheedom
Who am I?
Alex Theedom, Senior Java Developer
@alextheedom
Available at
Также доступен на
русском языке
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
What are you doing?
• Java Enterprise Edition (J2EE, EE 6/7)
• Spring
The beginning
•Design 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?
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
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
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 …
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;
Singleton Pattern
•Conclusions so far
•Very different implementation
•Substantially less boilerplate code
•Enhancements via specialized annotations
There’s more…
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
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
The Good, Bad and the Ugly
•The Bad:
•overuse can cause problems
•lazy loading causes delays
•eager loading causes memory problems
•And the ugly:
•considered an anti-pattern
•only niche use
•smarter to use a stateless session bean
The Good, Bad and the Ugly
Factory Pattern
•Creational pattern
•Interface for creating family of objects
•Clients are decoupled from the creation
•Can be implemented as singleton
Factory Pattern
•CDI framework operates like 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;
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?
?!?
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
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
}
Factory Pattern
•Annotate injection points
@Inject @SoftDrink
DrinksMachine softDrinksMachine;
@Inject @SoftDrink
DrinksMachine softDrinksMachine;
@Inject @Coffee
DrinksMachine coffeeDrinksMachine;
@Inject @Coffee
DrinksMachine coffeeDrinksMachine;
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
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;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface History
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface History
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;
}
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
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
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
Façade Pattern
•Encapsulates complicated logic
@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;
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
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
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();
}
}
•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
Observer Pattern
•Behavioural Pattern
•Publisher-Subscriber
•Classic implementation: Implement a Subscriber
interface, register with publisher and call a notify
method on subscribers
Observer Pattern
•Define an event class
public class MessageEvent {
private String message;
public MessageEvent(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
public class MessageEvent {
private String message;
public MessageEvent(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
Observer Pattern
•Notifies dependents of state change
@Stateless
public class MessageService {
@Inject
Event<MessageEvent> messageEvent;
public void fireMessage(){
messageEvent.fire(new MessageEvent("Hello World"));
}
}
@Stateless
public class MessageService {
@Inject
Event<MessageEvent> messageEvent;
public void fireMessage(){
messageEvent.fire(new MessageEvent("Hello World"));
}
}
Observer Pattern
•Dependent receives state change notification
@Stateless
public class MessageObserver {
public void listenToMessage(@Observes MessageEvent message){
System.out.println(message.getMessage());
}
}
@Stateless
public class MessageObserver {
public void listenToMessage(@Observes MessageEvent message){
System.out.println(message.getMessage());
}
}
Observer Pattern
•Qualifier to filter events
@WarningMessage
@Inject
Event<MessageEvent> messageEvent;
@WarningMessage
@Inject
Event<MessageEvent> messageEvent;
public void listenToMessage(
@Observes @WarningMessage MessageEvent message)
public void listenToMessage(
@Observes @WarningMessage MessageEvent message)
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
Final Conclusion
•Efficiency savings
•Greater control over behaviour
•New features enhance implementation
Q & A
Java EE
revisits design patterns
Alex Theedom @alextheedom

Weitere ähnliche Inhalte

Was ist angesagt?

Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
WO Community
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
WO Community
 
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Lucidworks
 

Was ist angesagt? (20)

Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Alfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy BehavioursAlfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy Behaviours
 
Practical ERSync
Practical ERSyncPractical ERSync
Practical ERSync
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
No Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with BootiqueNo Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with Bootique
 
EJB 3.2 - Java EE 7 - Java One Hyderabad 2012
EJB 3.2 - Java EE 7 - Java One Hyderabad 2012EJB 3.2 - Java EE 7 - Java One Hyderabad 2012
EJB 3.2 - Java EE 7 - Java One Hyderabad 2012
 
Fun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJBFun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJB
 
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
 
Devoxx UK 2015: How Java EE has changed pattern implementation
Devoxx UK 2015: How Java EE has changed pattern implementationDevoxx UK 2015: How Java EE has changed pattern implementation
Devoxx UK 2015: How Java EE has changed pattern implementation
 
Beyond Domino Designer
Beyond Domino DesignerBeyond Domino Designer
Beyond Domino Designer
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational Controls
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
 
Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6
 
Getting started with rails active storage wae
Getting started with rails active storage waeGetting started with rails active storage wae
Getting started with rails active storage wae
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 

Ähnlich wie Java EE revisits design patterns

DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻
都元ダイスケ Miyamoto
 

Ähnlich wie Java EE revisits design patterns (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"
 
Java EE changes design pattern implementation: JavaDays Kiev 2015
Java EE changes design pattern implementation: JavaDays Kiev 2015Java EE changes design pattern implementation: JavaDays Kiev 2015
Java EE changes design pattern implementation: JavaDays Kiev 2015
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF 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
 
JS Essence
JS EssenceJS Essence
JS Essence
 
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)
 
Agile sites311training
Agile sites311trainingAgile sites311training
Agile sites311training
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure Data
 
DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻
 
Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script Applications
 
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
 
Where to save my data, for devs!
Where to save my data, for devs!Where to save my data, for devs!
Where to save my data, for devs!
 
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
 
presentation
presentationpresentation
presentation
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9
 
Building a Simple Theme Framework
Building a Simple Theme FrameworkBuilding a Simple Theme Framework
Building a Simple Theme Framework
 
Grails 4 and Micronaut at Devnexus 2019
Grails 4 and Micronaut at Devnexus 2019Grails 4 and Micronaut at Devnexus 2019
Grails 4 and Micronaut at Devnexus 2019
 
presentation
presentationpresentation
presentation
 
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
 
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
 

Mehr von Alex Theedom

Mehr von Alex Theedom (9)

Build an Amazon Polly connector in 15 mins with MuleSoft
Build an Amazon Polly connector in 15 mins with MuleSoftBuild an Amazon Polly connector in 15 mins with MuleSoft
Build an Amazon Polly connector in 15 mins with MuleSoft
 
Java EE 8 security and JSON binding API
Java EE 8 security and JSON binding APIJava EE 8 security and JSON binding API
Java EE 8 security and JSON binding API
 
JDKIO: Java EE 8 what Servlet 4 and HTTP2 mean to you
JDKIO: Java EE 8 what Servlet 4 and HTTP2 mean to youJDKIO: Java EE 8 what Servlet 4 and HTTP2 mean to you
JDKIO: Java EE 8 what Servlet 4 and HTTP2 mean to you
 
Java EE 8: What Servlet 4.0 and HTTP2 mean to you
Java EE 8: What Servlet 4.0 and HTTP2 mean to youJava EE 8: What Servlet 4.0 and HTTP2 mean to you
Java EE 8: What Servlet 4.0 and HTTP2 mean to you
 
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 8: What Servlet 4.0 and HTTP/2 mean to you
Java EE 8: What Servlet 4.0 and HTTP/2 mean to youJava EE 8: What Servlet 4.0 and HTTP/2 mean to you
Java EE 8: What Servlet 4.0 and HTTP/2 mean to you
 
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"
 
Jersey Coders New Term Introduction
Jersey Coders New Term IntroductionJersey Coders New Term Introduction
Jersey Coders New Term Introduction
 
Java days Lviv 2015
Java days Lviv 2015Java days Lviv 2015
Java days Lviv 2015
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Java EE revisits design patterns

  • 1. Java EE revisits design patterns Alex Theedom @alextheedom
  • 2. Who am I? Alex Theedom, Senior Java Developer @alextheedom
  • 5. 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. What are you doing? • Java Enterprise Edition (J2EE, EE 6/7) • Spring
  • 7. The beginning •Design 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. 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. 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. 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. 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. Singleton Pattern •Conclusions so far •Very different implementation •Substantially less boilerplate code •Enhancements via specialized annotations There’s more…
  • 13. 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. 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. The Good, Bad and the Ugly •The Bad: •overuse can cause problems •lazy loading causes delays •eager loading causes memory problems
  • 16. •And the ugly: •considered an anti-pattern •only niche use •smarter to use a stateless session bean The Good, Bad and the Ugly
  • 17. Factory Pattern •Creational pattern •Interface for creating family of objects •Clients are decoupled from the creation •Can be implemented as singleton
  • 18. Factory Pattern •CDI framework operates like 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. 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. 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. 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. Factory Pattern •Annotate injection points @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine;
  • 23. 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. 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; @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface History @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface History
  • 25. 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. 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. 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. 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. Façade Pattern •Encapsulates complicated logic @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. 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. 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. 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. •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. Observer Pattern •Behavioural Pattern •Publisher-Subscriber •Classic implementation: Implement a Subscriber interface, register with publisher and call a notify method on subscribers
  • 35. Observer Pattern •Define an event class public class MessageEvent { private String message; public MessageEvent(String message){ this.message = message; } public String getMessage(){ return message; } } public class MessageEvent { private String message; public MessageEvent(String message){ this.message = message; } public String getMessage(){ return message; } }
  • 36. Observer Pattern •Notifies dependents of state change @Stateless public class MessageService { @Inject Event<MessageEvent> messageEvent; public void fireMessage(){ messageEvent.fire(new MessageEvent("Hello World")); } } @Stateless public class MessageService { @Inject Event<MessageEvent> messageEvent; public void fireMessage(){ messageEvent.fire(new MessageEvent("Hello World")); } }
  • 37. Observer Pattern •Dependent receives state change notification @Stateless public class MessageObserver { public void listenToMessage(@Observes MessageEvent message){ System.out.println(message.getMessage()); } } @Stateless public class MessageObserver { public void listenToMessage(@Observes MessageEvent message){ System.out.println(message.getMessage()); } }
  • 38. Observer Pattern •Qualifier to filter events @WarningMessage @Inject Event<MessageEvent> messageEvent; @WarningMessage @Inject Event<MessageEvent> messageEvent; public void listenToMessage( @Observes @WarningMessage MessageEvent message) public void listenToMessage( @Observes @WarningMessage MessageEvent message)
  • 39. 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
  • 40. Final Conclusion •Efficiency savings •Greater control over behaviour •New features enhance implementation
  • 41. Q & A
  • 42. Java EE revisits design patterns Alex Theedom @alextheedom

Hinweis der Redaktion

  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. 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 Software Development. 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 applications. 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 the Produces annotation in the implementation of the factory pattern. Beans or objects that you want to inject that do not conform to JSR299 uses the Produces 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 @DependsOn @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 forced 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 Calls 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 CDI. 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 -&amp;gt; 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 @Dependent. This means that every time we fetch an instance produced by some Producer method, the method will always be called.
  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. In GOF very simple really usually named service or façade assumed to be stateless Java EE gives us a marker annotation denotes it is a façade and stateless The simple definition is that it hides 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. 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 stateless 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 – container magic Implementation might be using things that are stateful By default transational – useful for this tier Includes: monitoring management, pooling 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. Because 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. @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. @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.
  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 You care about decoupling You want to change the observer that get triggered at runtime Antithetical to original goals -&amp;gt; implement interface on a bunch of objects and then on the listener you register the concrete imp of those instances. How does Java EE solve this? … 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 MessageEvent. We must fire an event by calling 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