SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

Model Gravitasi Hansen
Model Gravitasi Hansen Model Gravitasi Hansen
Model Gravitasi Hansen
Rizky Saputra
 

Andere mochten auch (14)

Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
 
Java EE 6 & GlassFish 3
Java EE 6 & GlassFish 3Java EE 6 & GlassFish 3
Java EE 6 & GlassFish 3
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design Patterns
 
SE2016 IoT Maksym Antipov "Hardware development as a hobby and a job"
SE2016 IoT Maksym Antipov "Hardware development as a hobby and a job"SE2016 IoT Maksym Antipov "Hardware development as a hobby and a job"
SE2016 IoT Maksym Antipov "Hardware development as a hobby and a job"
 
Java projectchangeworld
Java projectchangeworldJava projectchangeworld
Java projectchangeworld
 
Javaepic
JavaepicJavaepic
Javaepic
 
Hibernate
HibernateHibernate
Hibernate
 
SE2016 BigData Ievgen Vladimirov "Only cloud"
SE2016 BigData Ievgen Vladimirov "Only cloud"SE2016 BigData Ievgen Vladimirov "Only cloud"
SE2016 BigData Ievgen Vladimirov "Only cloud"
 
Javadesign
JavadesignJavadesign
Javadesign
 
Java encapsulation
Java encapsulationJava encapsulation
Java encapsulation
 
Javafeature
JavafeatureJavafeature
Javafeature
 
SE2016 Java Dmitriy Kouperman "Working with legacy systems. Stabilization, mo...
SE2016 Java Dmitriy Kouperman "Working with legacy systems. Stabilization, mo...SE2016 Java Dmitriy Kouperman "Working with legacy systems. Stabilization, mo...
SE2016 Java Dmitriy Kouperman "Working with legacy systems. Stabilization, mo...
 
Model Gravitasi Hansen
Model Gravitasi Hansen Model Gravitasi Hansen
Model Gravitasi Hansen
 

Ähnlich wie SE2016 Java Alex Theedom "Java EE revisits design patterns"

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
 

Ähnlich wie SE2016 Java 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 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
 
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
 
Attain Clean Code in Sitecore Solutions using Design Patterns
Attain Clean Code in Sitecore Solutions using Design PatternsAttain Clean Code in Sitecore Solutions using Design Patterns
Attain Clean Code in Sitecore Solutions using Design Patterns
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 

Mehr von Inhacking

Mehr von Inhacking (20)

SE2016 Fundraising Roman Kravchenko "Investment in Ukrainian IoT-Startups"
SE2016 Fundraising Roman Kravchenko "Investment in Ukrainian IoT-Startups"SE2016 Fundraising Roman Kravchenko "Investment in Ukrainian IoT-Startups"
SE2016 Fundraising Roman Kravchenko "Investment in Ukrainian IoT-Startups"
 
SE2016 Fundraising Wlodek Laskowski "Insider guide to successful fundraising ...
SE2016 Fundraising Wlodek Laskowski "Insider guide to successful fundraising ...SE2016 Fundraising Wlodek Laskowski "Insider guide to successful fundraising ...
SE2016 Fundraising Wlodek Laskowski "Insider guide to successful fundraising ...
 
SE2016 Fundraising Andrey Sobol "Blockchain Crowdfunding or "Mommy, look, I l...
SE2016 Fundraising Andrey Sobol "Blockchain Crowdfunding or "Mommy, look, I l...SE2016 Fundraising Andrey Sobol "Blockchain Crowdfunding or "Mommy, look, I l...
SE2016 Fundraising Andrey Sobol "Blockchain Crowdfunding or "Mommy, look, I l...
 
SE2016 Company Development Valentin Dombrovsky "Travel startups challenges an...
SE2016 Company Development Valentin Dombrovsky "Travel startups challenges an...SE2016 Company Development Valentin Dombrovsky "Travel startups challenges an...
SE2016 Company Development Valentin Dombrovsky "Travel startups challenges an...
 
SE2016 Company Development Vadym Gorenko "How to pass the death valley"
SE2016 Company Development Vadym Gorenko  "How to pass the death valley"SE2016 Company Development Vadym Gorenko  "How to pass the death valley"
SE2016 Company Development Vadym Gorenko "How to pass the death valley"
 
SE2016 Marketing&PR Jan Keil "Do the right thing marketing for startups"
SE2016 Marketing&PR Jan Keil "Do the right thing marketing for startups"SE2016 Marketing&PR Jan Keil "Do the right thing marketing for startups"
SE2016 Marketing&PR Jan Keil "Do the right thing marketing for startups"
 
SE2016 PR&Marketing Mikhail Patalakha "ASO how to start and how to finish"
SE2016 PR&Marketing Mikhail Patalakha "ASO how to start and how to finish"SE2016 PR&Marketing Mikhail Patalakha "ASO how to start and how to finish"
SE2016 PR&Marketing Mikhail Patalakha "ASO how to start and how to finish"
 
SE2016 UI/UX Alina Kononenko "Designing for Apple Watch and Apple TV"
SE2016 UI/UX Alina Kononenko "Designing for Apple Watch and Apple TV"SE2016 UI/UX Alina Kononenko "Designing for Apple Watch and Apple TV"
SE2016 UI/UX Alina Kononenko "Designing for Apple Watch and Apple TV"
 
SE2016 Management Mikhail Lebedinkiy "iAIST the first pure ukrainian corporat...
SE2016 Management Mikhail Lebedinkiy "iAIST the first pure ukrainian corporat...SE2016 Management Mikhail Lebedinkiy "iAIST the first pure ukrainian corporat...
SE2016 Management Mikhail Lebedinkiy "iAIST the first pure ukrainian corporat...
 
SE2016 Management Anna Lavrova "Gladiator in the suit crisis is our brand!"
SE2016 Management Anna Lavrova "Gladiator in the suit  crisis is our brand!"SE2016 Management Anna Lavrova "Gladiator in the suit  crisis is our brand!"
SE2016 Management Anna Lavrova "Gladiator in the suit crisis is our brand!"
 
SE2016 Management Aleksey Solntsev "Management of the projects in the conditi...
SE2016 Management Aleksey Solntsev "Management of the projects in the conditi...SE2016 Management Aleksey Solntsev "Management of the projects in the conditi...
SE2016 Management Aleksey Solntsev "Management of the projects in the conditi...
 
SE2016 Management Vitalii Laptenok "Processes and planning for a product comp...
SE2016 Management Vitalii Laptenok "Processes and planning for a product comp...SE2016 Management Vitalii Laptenok "Processes and planning for a product comp...
SE2016 Management Vitalii Laptenok "Processes and planning for a product comp...
 
SE2016 Management Yana Prolis "Please don't burn down!"
SE2016 Management Yana Prolis "Please don't burn down!"SE2016 Management Yana Prolis "Please don't burn down!"
SE2016 Management Yana Prolis "Please don't burn down!"
 
SE2016 Management Marina Bril "Management at marketing teams and performance"
SE2016 Management Marina Bril "Management at marketing teams and performance"SE2016 Management Marina Bril "Management at marketing teams and performance"
SE2016 Management Marina Bril "Management at marketing teams and performance"
 
SE2016 iOS Anton Fedorchenko "Swift for Server-side Development"
SE2016 iOS Anton Fedorchenko "Swift for Server-side Development"SE2016 iOS Anton Fedorchenko "Swift for Server-side Development"
SE2016 iOS Anton Fedorchenko "Swift for Server-side Development"
 
SE2016 iOS Alexander Voronov "Test driven development in real world"
SE2016 iOS Alexander Voronov "Test driven development in real world"SE2016 iOS Alexander Voronov "Test driven development in real world"
SE2016 iOS Alexander Voronov "Test driven development in real world"
 
SE2016 JS Gregory Shehet "Undefined on prod, or how to test a react application"
SE2016 JS Gregory Shehet "Undefined on prod, or how to test a react application"SE2016 JS Gregory Shehet "Undefined on prod, or how to test a react application"
SE2016 JS Gregory Shehet "Undefined on prod, or how to test a react application"
 
SE2016 JS Alexey Osipenko "Basics of functional reactive programming"
SE2016 JS Alexey Osipenko "Basics of functional reactive programming"SE2016 JS Alexey Osipenko "Basics of functional reactive programming"
SE2016 JS Alexey Osipenko "Basics of functional reactive programming"
 
SE2016 Java Vladimir Mikhel "Scrapping the web"
SE2016 Java Vladimir Mikhel "Scrapping the web"SE2016 Java Vladimir Mikhel "Scrapping the web"
SE2016 Java Vladimir Mikhel "Scrapping the web"
 
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
 

KĂźrzlich hochgeladen

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

KĂźrzlich hochgeladen (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 

SE2016 Java 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