SlideShare ist ein Scribd-Unternehmen logo
1 von 41
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 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?
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
•Simplified 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 destroyed 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
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;
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 // or @Named("History")
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@History // or @Named("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, @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;
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?

Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemRami Sayar
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Wen-Tien Chang
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and ActivatorKevin Webber
 
04 integrate entityframework
04 integrate entityframework04 integrate entityframework
04 integrate entityframeworkErhwen Kuo
 
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 AppAll Things Open
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewCraig Dickson
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With JestBen McCormick
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Ngoc Dao
 
Alfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy BehavioursAlfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy BehavioursJ V
 
Using ActiveObjects in Atlassian Plugins
Using ActiveObjects in Atlassian PluginsUsing ActiveObjects in Atlassian Plugins
Using ActiveObjects in Atlassian PluginsAtlassian
 
All your data belong to us - The Active Objects Plugin
All your data belong to us - The Active Objects PluginAll your data belong to us - The Active Objects Plugin
All your data belong to us - The Active Objects PluginSamuel Le Berrigaud
 
Modern javascript
Modern javascriptModern javascript
Modern javascriptKevin Ball
 
Building and Managing Projects with Maven
Building and Managing Projects with MavenBuilding and Managing Projects with Maven
Building and Managing Projects with MavenKhan625
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumNgoc Dao
 
06 integrate elasticsearch
06 integrate elasticsearch06 integrate elasticsearch
06 integrate elasticsearchErhwen Kuo
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesBrett Meyer
 

Was ist angesagt? (20)

Agile sites @ telmore
Agile sites @ telmore Agile sites @ telmore
Agile sites @ telmore
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React Ecosystem
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
 
04 integrate entityframework
04 integrate entityframework04 integrate entityframework
04 integrate entityframework
 
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
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014
 
Alfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy BehavioursAlfresco Content Modelling and Policy Behaviours
Alfresco Content Modelling and Policy Behaviours
 
Using ActiveObjects in Atlassian Plugins
Using ActiveObjects in Atlassian PluginsUsing ActiveObjects in Atlassian Plugins
Using ActiveObjects in Atlassian Plugins
 
All your data belong to us - The Active Objects Plugin
All your data belong to us - The Active Objects PluginAll your data belong to us - The Active Objects Plugin
All your data belong to us - The Active Objects Plugin
 
Modern javascript
Modern javascriptModern javascript
Modern javascript
 
Building and Managing Projects with Maven
Building and Managing Projects with MavenBuilding and Managing Projects with Maven
Building and Managing Projects with Maven
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
 
06 integrate elasticsearch
06 integrate elasticsearch06 integrate elasticsearch
06 integrate elasticsearch
 
[2015/2016] Backbone JS
[2015/2016] Backbone JS[2015/2016] Backbone JS
[2015/2016] Backbone JS
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
 

Andere mochten auch

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
 
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
 
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 implementationAlex Theedom
 
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
 
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 2015Alex Theedom
 
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...Yaroslav Yermilov
 
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
 
Get along with JHipster
Get along with JHipsterGet along with JHipster
Get along with JHipsterDmytro Panin
 
JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?Edward Burns
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)Pavel Bucek
 
CON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To YouCON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To YouEdward Burns
 
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 youAlex Theedom
 

Andere mochten auch (14)

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
 
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
 
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
 
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"
 
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
 
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
 
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
 
Get along with JHipster
Get along with JHipsterGet along with JHipster
Get along with JHipster
 
jDays Sweden 2016
jDays Sweden 2016jDays Sweden 2016
jDays Sweden 2016
 
JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
 
CON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To YouCON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To You
 
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
 

Ähnlich wie 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"
SE2016 Java Alex Theedom "Java EE revisits design patterns"Inhacking
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsMurat Yener
 
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
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻都元ダイスケ Miyamoto
 
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
 
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
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure DataTaro L. Saito
 
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...HostedbyConfluent
 
Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsFabian Jakobs
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Derek Jacoby
 
Writing an extensible web testing framework ready for the cloud slide share
Writing an extensible web testing framework ready for the cloud   slide shareWriting an extensible web testing framework ready for the cloud   slide share
Writing an extensible web testing framework ready for the cloud slide shareMike Ensor
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Doris Chen
 
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
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 

Ä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"
 
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
 
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
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻
 
Agile sites311training
Agile sites311trainingAgile sites311training
Agile sites311training
 
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)
 
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
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure Data
 
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...
 
Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script Applications
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9
 
Writing an extensible web testing framework ready for the cloud slide share
Writing an extensible web testing framework ready for the cloud   slide shareWriting an extensible web testing framework ready for the cloud   slide share
Writing an extensible web testing framework ready for the cloud slide share
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
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
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 

Kürzlich hochgeladen

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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 organizationRadu Cotescu
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

Java EE revisits design patterns

  • 1. Java EE revisits design patterns Alex Theedom @alextheedom
  • 2. Who am I? Alex Theedom, Senior Java Developer @alextheedom
  • 4. 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
  • 5. What are you doing? • Java Enterprise Edition (J2EE, EE 6/7) • Spring
  • 6. 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?
  • 7. 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
  • 8. Java EE Programming Model •Simplified 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
  • 9. Singleton Pattern •Creational pattern •Single instance and instantiated once •Must be thread safe •Not normally destroyed during application life cycle •Classic implementation: private constructor, double locking, static initializer, enums …
  • 10. 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;
  • 11. Singleton Pattern •Conclusions so far •Very different implementation •Substantially less boilerplate code •Enhancements via specialized annotations There’s more…
  • 12. 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
  • 13. 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
  • 14. The Good, Bad and the Ugly •The Bad: •overuse can cause problems •lazy loading causes delays •eager loading causes memory problems
  • 15. •And the ugly: •considered an anti-pattern •only niche use •smarter to use a stateless session bean The Good, Bad and the Ugly
  • 16. Factory Pattern •Creational pattern •Interface for creating family of objects •Clients are decoupled from the creation
  • 17. 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;
  • 18. 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? ?!?
  • 19. 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
  • 20. 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 }
  • 21. Factory Pattern •Annotate injection points @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine;
  • 22. 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
  • 23. Factory Pattern •Dive deeper •Producer methods •Use it like so: @History // or @Named("History") @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @History // or @Named("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
  • 24. 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; }
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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;
  • 29. 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
  • 30. 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
  • 31. 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(); } }
  • 32. •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
  • 33. Observer Pattern •Behavioural Pattern •Publisher-Subscriber •Classic implementation: Implement a Subscriber interface, register with publisher and call a notify method on subscribers
  • 34. 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; } }
  • 35. 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")); } }
  • 36. 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()); } }
  • 37. 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)
  • 38. 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. Final Conclusion •Efficiency savings •Greater control over behaviour •New features enhance implementation
  • 40. Q & A
  • 41. 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.
  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 framework, 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 getMessage must wait until the addMessage method completes 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 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 / static class – 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 in java EE, 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 that Java EE 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 @History. 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 in simplistic terms, but the underlying code is non-trival. GOF fashion. Simple just name service o façade Java EE special annotation, marker annotation 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. 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 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 By default transactional 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. Does not require changes to legacy code 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. First of all you need to define an event class that gets fired. This signals that an event has occurred and functions as a payload for the observer.
  27. 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.
  28. 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.
  29. 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