SlideShare a Scribd company logo
Java EE
revisits design patterns
Sep. 2-4
Kyiv, Desyatynna str. 12
@readlearncode
Alex Theedom Senior Java Developer
Who am I?
Alex Theedom, Senior Java Developer
@readlearncode
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
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
}
}
@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() {}
}
•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
}
•Use it like so:
@Inject
DrinksMachine drinksMachine;
Factory Pattern
•Problem! Multiple concrete implementations
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
public class SoftDrinksMachine implements DrinksMachine {
// Implementation code
}
@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 Coffee
Factory Pattern
•Annotate respective classes
@Coffee
public class CoffeeMachine implements DrinksMachine {
// Implementation code
}
@SoftDrink
public class SoftDrinksMachine implements DrinksMachine {
// Implementation code
}
Factory Pattern
•Annotate injection points
@Inject @SoftDrink
DrinksMachine softDrinksMachine;
@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
@Inject
List<Books> library;
@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;
}
The Good, Bad and the Ugly
•The Good:
•easy to implement
•no boilerplate code
•works magically
•any object can be made injectable
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
}
}
@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();
}
}
•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;
}
}
Observer Pattern
•Notifies dependents of state change
@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());
}
}
Observer Pattern
•Qualifier to filter events
@WarningMessage
@Inject
Event<MessageEvent> messageEvent;
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
Entity
•Lightweight domain object which is persistable
•Annotated with javax.persistence.Entity
•Can represent relational data object/relational mapping
annotations
Entity
@Entity
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
}
Final Conclusion
•Efficiency savings
•Greater control over behaviour
•New features enhance implementation
Q & A
Thank You
Sep. 2-4
Kyiv, Desyatynna str. 12
@readlearncode
Alex Theedom Senior Java Developer

More Related Content

What's hot

Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter Bonfire
Jeff Fox
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
Steven Smith
 
44 Slides About 22 Modules
44 Slides About 22 Modules44 Slides About 22 Modules
44 Slides About 22 Modules
heyrocker
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
Steven Smith
 
Zero redeployment with JRebel
Zero redeployment with JRebelZero redeployment with JRebel
Zero redeployment with JRebel
Minh Hoang
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Steven Smith
 
"Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,...
"Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,..."Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,...
"Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,...
Yandex
 
Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Do we need SOLID principles during software development?
Do we need SOLID principles during software development?
Anna Shymchenko
 
.NET executable requirements
.NET executable requirements.NET executable requirements
.NET executable requirements
Godfrey Nolan
 
AtlasCamp US 2012 Keynote, Jean-Michel Lemieux
AtlasCamp US 2012 Keynote, Jean-Michel LemieuxAtlasCamp US 2012 Keynote, Jean-Michel Lemieux
AtlasCamp US 2012 Keynote, Jean-Michel Lemieux
Atlassian
 
Ten Advices for Architects
Ten Advices for ArchitectsTen Advices for Architects
Ten Advices for Architects
Eberhard Wolff
 
Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...
Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...
Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...Atlassian
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
guy_davis
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
Huy Hoàng Phạm
 
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptxDSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
Mikalai Alimenkou
 
Java Concurrent
Java ConcurrentJava Concurrent
Java Concurrent
NexThoughts Technologies
 
Developing for Remote Bamboo Agents, AtlasCamp US 2012
Developing for Remote Bamboo Agents, AtlasCamp US 2012Developing for Remote Bamboo Agents, AtlasCamp US 2012
Developing for Remote Bamboo Agents, AtlasCamp US 2012
Atlassian
 
CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287
Ahmad Gohar
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
apoorvams
 
every-day-automation
every-day-automationevery-day-automation
every-day-automation
Amir Barylko
 

What's hot (20)

Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter Bonfire
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
44 Slides About 22 Modules
44 Slides About 22 Modules44 Slides About 22 Modules
44 Slides About 22 Modules
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
 
Zero redeployment with JRebel
Zero redeployment with JRebelZero redeployment with JRebel
Zero redeployment with JRebel
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
"Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,...
"Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,..."Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,...
"Architecting and testing large iOS apps: lessons from Facebook". Adam Ernst,...
 
Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Do we need SOLID principles during software development?
Do we need SOLID principles during software development?
 
.NET executable requirements
.NET executable requirements.NET executable requirements
.NET executable requirements
 
AtlasCamp US 2012 Keynote, Jean-Michel Lemieux
AtlasCamp US 2012 Keynote, Jean-Michel LemieuxAtlasCamp US 2012 Keynote, Jean-Michel Lemieux
AtlasCamp US 2012 Keynote, Jean-Michel Lemieux
 
Ten Advices for Architects
Ten Advices for ArchitectsTen Advices for Architects
Ten Advices for Architects
 
Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...
Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...
Expose Yourself! How to Leverage Plugin Extensibility to Delight your Users, ...
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptxDSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
 
Java Concurrent
Java ConcurrentJava Concurrent
Java Concurrent
 
Developing for Remote Bamboo Agents, AtlasCamp US 2012
Developing for Remote Bamboo Agents, AtlasCamp US 2012Developing for Remote Bamboo Agents, AtlasCamp US 2012
Developing for Remote Bamboo Agents, AtlasCamp US 2012
 
CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
every-day-automation
every-day-automationevery-day-automation
every-day-automation
 

Similar to Alex Theedom Java ee revisits design patterns

Java EE revisits design patterns
Java EE revisits design patternsJava EE revisits design patterns
Java EE revisits design patterns
Alex Theedom
 
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
Alex Theedom
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
Alex Theedom
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns
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 2015
Alex Theedom
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design Patterns
Murat Yener
 
jDays Sweden 2016
jDays Sweden 2016jDays Sweden 2016
jDays Sweden 2016
Alex Theedom
 
Sitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helixSitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helix
Peter Nazarov
 
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
 
Features, Exportables & You
Features, Exportables & YouFeatures, Exportables & You
Features, Exportables & You
jskulski
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
Amr Abd El Latief
 
New life inside monolithic application
New life inside monolithic applicationNew life inside monolithic application
New life inside monolithic application
Taras Matyashovsky
 
Component-first Applications
Component-first ApplicationsComponent-first Applications
Component-first Applications
Miguelangel Fernandez
 
Angular 2 overview
Angular 2 overviewAngular 2 overview
Angular 2 overview
Jesse Warden
 
Vs11 overview
Vs11 overviewVs11 overview
Vs11 overview
ravclarke
 
NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET Dmytro Mindra
 
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
Gil Fink
 
Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014
Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014
Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014
Phil Leggetter
 
Building a Simple Theme Framework
Building a Simple Theme FrameworkBuilding a Simple Theme Framework
Building a Simple Theme Framework
Joe Casabona
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developed
Alexander Makarov
 

Similar to Alex Theedom Java ee revisits design patterns (20)

Java EE revisits design patterns
Java EE revisits design patternsJava EE revisits design patterns
Java EE revisits design patterns
 
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 Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
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
 
jDays Sweden 2016
jDays Sweden 2016jDays Sweden 2016
jDays Sweden 2016
 
Sitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helixSitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helix
 
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)
 
Features, Exportables & You
Features, Exportables & YouFeatures, Exportables & You
Features, Exportables & You
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
New life inside monolithic application
New life inside monolithic applicationNew life inside monolithic application
New life inside monolithic application
 
Component-first Applications
Component-first ApplicationsComponent-first Applications
Component-first Applications
 
Angular 2 overview
Angular 2 overviewAngular 2 overview
Angular 2 overview
 
Vs11 overview
Vs11 overviewVs11 overview
Vs11 overview
 
NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET
 
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
 
Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014
Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014
Using BladeRunnerJS to Build Front-End Apps that Scale - Fluent 2014
 
Building a Simple Theme Framework
Building a Simple Theme FrameworkBuilding a Simple Theme Framework
Building a Simple Theme Framework
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developed
 

More from Аліна Шепшелей

Vladimir Lozanov How to deliver high quality apps to the app store
Vladimir Lozanov	How to deliver high quality apps to the app storeVladimir Lozanov	How to deliver high quality apps to the app store
Vladimir Lozanov How to deliver high quality apps to the app store
Аліна Шепшелей
 
Oleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile projectOleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile project
Аліна Шепшелей
 
Alexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real worldAlexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real world
Аліна Шепшелей
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Аліна Шепшелей
 
Valerii Iakovenko Drones as the part of the present
Valerii Iakovenko	Drones as the part of the presentValerii Iakovenko	Drones as the part of the present
Valerii Iakovenko Drones as the part of the present
Аліна Шепшелей
 
Valerii Moisieienko Apache hbase workshop
Valerii Moisieienko	Apache hbase workshopValerii Moisieienko	Apache hbase workshop
Valerii Moisieienko Apache hbase workshop
Аліна Шепшелей
 
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Аліна Шепшелей
 
Anton Ivinskyi Application level metrics and performance tests
Anton Ivinskyi	Application level metrics and performance testsAnton Ivinskyi	Application level metrics and performance tests
Anton Ivinskyi Application level metrics and performance tests
Аліна Шепшелей
 
Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?
Аліна Шепшелей
 
Макс Семенчук Дизайнер, которому доверяют
 Макс Семенчук Дизайнер, которому доверяют Макс Семенчук Дизайнер, которому доверяют
Макс Семенчук Дизайнер, которому доверяют
Аліна Шепшелей
 
Anton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designersAnton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designers
Аліна Шепшелей
 
Andrew Veles Product design is about the process
Andrew Veles Product design is about the processAndrew Veles Product design is about the process
Andrew Veles Product design is about the process
Аліна Шепшелей
 
Kononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TVKononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TV
Аліна Шепшелей
 
Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?
Аліна Шепшелей
 
Gregory Shehet Undefined' on prod, or how to test a react app
Gregory Shehet Undefined' on  prod, or how to test a react appGregory Shehet Undefined' on  prod, or how to test a react app
Gregory Shehet Undefined' on prod, or how to test a react app
Аліна Шепшелей
 
Alexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programmingAlexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programming
Аліна Шепшелей
 
Vladimir Mikhel Scrapping the web
Vladimir Mikhel Scrapping the web Vladimir Mikhel Scrapping the web
Vladimir Mikhel Scrapping the web
Аліна Шепшелей
 
Roman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your dbRoman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your db
Аліна Шепшелей
 
Dmutro Panin JHipster
Dmutro Panin JHipster Dmutro Panin JHipster
Dmutro Panin JHipster
Аліна Шепшелей
 
Alexey Tokar To find a needle in a haystack
Alexey Tokar To find a needle in a haystackAlexey Tokar To find a needle in a haystack
Alexey Tokar To find a needle in a haystack
Аліна Шепшелей
 

More from Аліна Шепшелей (20)

Vladimir Lozanov How to deliver high quality apps to the app store
Vladimir Lozanov	How to deliver high quality apps to the app storeVladimir Lozanov	How to deliver high quality apps to the app store
Vladimir Lozanov How to deliver high quality apps to the app store
 
Oleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile projectOleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile project
 
Alexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real worldAlexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real world
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
Valerii Iakovenko Drones as the part of the present
Valerii Iakovenko	Drones as the part of the presentValerii Iakovenko	Drones as the part of the present
Valerii Iakovenko Drones as the part of the present
 
Valerii Moisieienko Apache hbase workshop
Valerii Moisieienko	Apache hbase workshopValerii Moisieienko	Apache hbase workshop
Valerii Moisieienko Apache hbase workshop
 
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
 
Anton Ivinskyi Application level metrics and performance tests
Anton Ivinskyi	Application level metrics and performance testsAnton Ivinskyi	Application level metrics and performance tests
Anton Ivinskyi Application level metrics and performance tests
 
Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?
 
Макс Семенчук Дизайнер, которому доверяют
 Макс Семенчук Дизайнер, которому доверяют Макс Семенчук Дизайнер, которому доверяют
Макс Семенчук Дизайнер, которому доверяют
 
Anton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designersAnton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designers
 
Andrew Veles Product design is about the process
Andrew Veles Product design is about the processAndrew Veles Product design is about the process
Andrew Veles Product design is about the process
 
Kononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TVKononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TV
 
Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?
 
Gregory Shehet Undefined' on prod, or how to test a react app
Gregory Shehet Undefined' on  prod, or how to test a react appGregory Shehet Undefined' on  prod, or how to test a react app
Gregory Shehet Undefined' on prod, or how to test a react app
 
Alexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programmingAlexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programming
 
Vladimir Mikhel Scrapping the web
Vladimir Mikhel Scrapping the web Vladimir Mikhel Scrapping the web
Vladimir Mikhel Scrapping the web
 
Roman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your dbRoman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your db
 
Dmutro Panin JHipster
Dmutro Panin JHipster Dmutro Panin JHipster
Dmutro Panin JHipster
 
Alexey Tokar To find a needle in a haystack
Alexey Tokar To find a needle in a haystackAlexey Tokar To find a needle in a haystack
Alexey Tokar To find a needle in a haystack
 

Recently uploaded

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 

Recently uploaded (20)

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 

Alex Theedom Java ee revisits design patterns

  • 1. Java EE revisits design patterns Sep. 2-4 Kyiv, Desyatynna str. 12 @readlearncode Alex Theedom Senior Java Developer
  • 2. Who am I? Alex Theedom, Senior Java Developer @readlearncode
  • 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
  • 9. 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 …
  • 10. Singleton Pattern @DependsOn("DatabaseConnectionBean") @Startup @Singleton public class Logger { @PostConstruct void constructExpensiveObject() { // Expensive construction } } @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() {} } •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 } •Use it like so: @Inject DrinksMachine drinksMachine;
  • 18. Factory Pattern •Problem! Multiple concrete implementations public class CoffeeMachine implements DrinksMachine { // Implementation code } public class SoftDrinksMachine implements DrinksMachine { // Implementation code } @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 Coffee
  • 20. Factory Pattern •Annotate respective classes @Coffee public class CoffeeMachine implements DrinksMachine { // Implementation code } @SoftDrink public class SoftDrinksMachine implements DrinksMachine { // Implementation code }
  • 21. Factory Pattern •Annotate injection points @Inject @SoftDrink DrinksMachine softDrinksMachine; @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 @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @History @Inject List<Books> library; @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; }
  • 25. The Good, Bad and the Ugly •The Good: •easy to implement •no boilerplate code •works magically •any object can be made injectable
  • 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 } } @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(); } }
  • 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; } }
  • 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")); } }
  • 36. Observer Pattern •Dependent receives state change notification @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; 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. Entity •Lightweight domain object which is persistable •Annotated with javax.persistence.Entity •Can represent relational data object/relational mapping annotations
  • 40. Entity @Entity public class Contact { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; }
  • 41. Final Conclusion •Efficiency savings •Greater control over behaviour •New features enhance implementation
  • 42. Q & A
  • 43. Thank You Sep. 2-4 Kyiv, Desyatynna str. 12 @readlearncode Alex Theedom Senior Java Developer