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
• Java EE Programming Model
• Singleton, Factory, Façade, Decorator and Observer
• Final Conclusions
• Q&A
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 destroy during application life cycle
•Classic implementation: private constructor, double
locking, static initializer, enums …
Singleton Pattern
@DependsOn("DatabaseConnectionBean")
@Startup
@Singleton
public class Logger {
@PostConstruct
void constructExpensiveObject() {
// Expensive construction
}
}
@DependsOn("DatabaseConnectionBean")
@Startup
@Singleton
public class Logger {
@PostConstruct
void constructExpensiveObject() {
// Expensive construction
}
}
@Inject
Logger logger;
@Inject
Logger logger;
Singleton Pattern
•Conclusions so far
•Very different implementation
•Substantially less boilerplate code
•Enhancements via specialized annotations
There’s more…
Singleton Pattern
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Logger {
@AccessTimeout(value = 30, unit=TimeUnit.SECONDS)
@Lock(LockType.WRITE)
public void addMessage(String message) {}
@Lock(LockType.READ)
public String getMessage() {}
}
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Logger {
@AccessTimeout(value = 30, unit=TimeUnit.SECONDS)
@Lock(LockType.WRITE)
public void addMessage(String message) {}
@Lock(LockType.READ)
public String getMessage() {}
}
•Container/bean managed concurrency
The Good, Bad and the Ugly
•The Good:
•enhancements via specialized annotations
•startup behavioural characteristics
•fine grain control over concurrency and access
timeout
•substantially less boilerplate code
The Good, Bad and the Ugly
•The Bad:
•overuse can cause problems
•lazy loading causes delays
•eager loading causes memory problems
•And the ugly:
•considered an anti-pattern
•only niche use
•smarter to use a stateless session bean
The Good, Bad and the Ugly
Factory Pattern
•Creational pattern
•Interface for creating family of objects
•Clients are decoupled from the creation
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
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@History
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@History
@Inject
List<Books> library;
@History
@Inject
List<Books> library;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface History
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface History
Factory Pattern
•Scope
•Determines when method called
•Life of object: @RequestScoped -> @ApplicationScoped
@RequestScoped
@History
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
@RequestScoped
@History
@Produces
public List<Book> getLibrary(){
// Generate a List of books called 'library'
return library;
}
The Good, Bad and the Ugly
•The Good:
•easy to implement
•no boilerplate code
•works magically
•any object can be made injectable
•automatic per class configuration
•Disambiguation/filtration via qualifiers
The Good, Bad and the Ugly
•The Bad: named annotation is not type safe
@Named("History") -> @History
•and the ugly: object creation hidden, hard to follow
execution flow, IDE should help
Façade Pattern
•Hides the complex logic and provides the interface for
the client
•Typically used in APIs
•Classic implementation: Just create a method to hide
complexity
Façade Pattern
•Encapsulates complicated logic
•@Stateless, @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
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
Thank You
Sep. 2-4
Kyiv, Desyatynna str. 12
@readlearncode
Alex Theedom Senior Java Developer

More Related Content

SE2016 - Java EE revisits design patterns 2016

  • 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 • Java EE Programming Model • Singleton, Factory, Façade, Decorator and Observer • Final Conclusions • Q&A
  • 5. 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?
  • 6. 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
  • 7. 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
  • 8. 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 …
  • 9. 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;
  • 10. Singleton Pattern •Conclusions so far •Very different implementation •Substantially less boilerplate code •Enhancements via specialized annotations There’s more…
  • 11. 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
  • 12. 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
  • 13. The Good, Bad and the Ugly •The Bad: •overuse can cause problems •lazy loading causes delays •eager loading causes memory problems
  • 14. •And the ugly: •considered an anti-pattern •only niche use •smarter to use a stateless session bean The Good, Bad and the Ugly
  • 15. Factory Pattern •Creational pattern •Interface for creating family of objects •Clients are decoupled from the creation
  • 16. 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;
  • 17. 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? ?!?
  • 18. 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
  • 19. 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 }
  • 20. Factory Pattern •Annotate injection points @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine;
  • 21. 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
  • 22. Factory Pattern •Dive deeper •Producer methods •Use it like so: @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @History @Inject List<Books> library; @History @Inject List<Books> library; @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface History @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface History
  • 23. 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; }
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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;
  • 28. 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
  • 29. Decorator Pattern •Structural Pattern •Dynamically adds logic to an object at runtime •More flexible that inheritance •Classic implementation
  • 30. 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(); } }
  • 31. •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
  • 32. Observer Pattern •Behavioural Pattern •Publisher-Subscriber •Classic implementation: Implement a Subscriber interface, register with publisher and call a notify method on subscribers
  • 33. 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; } }
  • 34. 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")); } }
  • 35. 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()); } }
  • 36. 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)
  • 37. 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
  • 38. Final Conclusion •Efficiency savings •Greater control over behaviour •New features enhance implementation
  • 39. Q & A
  • 40. Thank You Sep. 2-4 Kyiv, Desyatynna str. 12 @readlearncode Alex Theedom Senior Java Developer

Editor's Notes

  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 Did they just appear overnight? Where did they come from? In fact design patterns have a long history starting way before computing, in architecture. That’s the construction type of architecture. But it wasn&amp;apos;t 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 application. However, we need to take care not to overuse design patterns. Unnecessary use of patterns tends to overcomplicate code making it hard to maintain and a poor design pattern knowledge leads to the inappropriate implementation of patterns to problems that they were not designed to solve. It is very much the case that: If the only tool you have is a hammer, then you will see every problem as a nail. The book&amp;apos;s authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.
  4. After 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. 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. 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, 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 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. Now lets look at how Java EE gives you even greater control over the pattern’s behaviour. Remember that I mentioned that the singleton bean is thread safe by default as concurrency is managed by the container. Well, Java EE offers two types of concurrency management: container managed and bean managed concurrency. By default the container manages the concurrency, removing the need to implement the usual concurrency solutions. @ConcurrentManagement However we are given the option to manage it ourselves by choosing bean managed concurrency. Add the annotation ConcurrencyManagementType.BEAN to the class definition. We still need to be careful with method access as our bean is exposed to a concurrent environment. Two lock types control access to the beans business method: WRITE and READ. @Lock Methods annotated WRITE, lock to other beans while being invoked. Methods that affect change will be annotated this way. Methods annotated READ allow concurrent access. In this code snippet, a call to the getMessage method will be forced to wait until the addMessage method completes. This may result in a ConcurrentAccessTimeoutException if the addMessage() method does not complete within the specified timeout period. @AccessTimeout The timeout period can be configured with an annotation either at the class level or the method level.
  10. 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. 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. Code 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. 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.
  13. Qualifiers are custom annotations that mark the concrete class and the point where you want the container to inject the object. 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. 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. We have seen how Java EE’s CDI framework 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. Java EE has a feature called producer methods. These methods provide a way to instantiate and therefore make available for injection objects that don’t conform to the managed bean specifications such as objects which require a constructor parameter for proper instantiation. Objects whose value might change at runtime and objects whose creation requires some customised initialization can also be produced ready for injection via a producer method. Lets have a look at a producer method which produces a List populated with Books objects. A list of Book objects will be injected into the injection point annotated @Library. Qualifier We can even use qualifiers to specify which List of books we wish to inject. Scope 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 has the same scope as 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. 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. For example: make an order, get a list of products, match given search criteria. Its a high level API that describe the middle tier of your application. That is really want you are doing with the façade, describing these high level abstractions to any user above that layer, perhaps a GUI layer or remote service invocation, they are talking in very simplistic terms to the facade and telling it please do this. The underlining code for that would be non-trival and fairly complex. How do you do this in classic GOF fashion, really not very difficult at all, they are general assumed to be stateless objects often named service or facade and you create essentially atomic methods that do a single thing. That is generally how it is implemented in GOF. What does Java EE give you? In this case Java EE has a specialised annotation, the annotation that I talked about before, that is the stateless annotation. It is essentially a marker to denote that this is a facade and that it is intended to be statelesss and to describe atomic operations at the application layer. It can do some very useful things.
  22. @Stateless Inject to use Entirely thread safe – not a singleton Implementation might be using things that are stateful It is entirely thread safe, when you access it, it will be thread safe but it is not a singleton. How it is made thread safe despite not being a singleton, that is beyond the scope of this talk, but essentially it involves some container magic. It is thread safe and stateless, you will never run into thread safety problems, it is by default transactional and it is useful for that tier of your application as you would normally want those high level use cases to be transactional, also it includes things like monitoring management as well as pooling and more importantly defining upper threshold for pool sizes for these services. It is very useful for defining high-level scalable APIs. It is stateless in terms of what the API expectations are. The implementation may be using things that are stateful for example you might have a entity manager that connects to a database. The thread safety is to shield the implementation from any issues 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 10,000 orders to process concurrently, because this object has an implicit upper bound you won&amp;apos;t run into a thread starvation situation. It will only be processed within the upper bounds of that thread pool which is typically 10, 15, 100 threads.
  23. The decorator pattern is one of the GOF Structural Pattern and dynamically adds logic to an object. Instead of inheritance the decorator adds functionality at run time. They introduce a huge amount of flexibility. Classical: Both decorator and target object must implement the same interface. Decorator  wraps the target object and adds its own behaviour. Can be really powerful.
  24. @Decorator @Delegate @Any Add the Decorator annotation to mark the class that will perform the decorating task and the Delegate and Any annotations to the target object. This is where the objects to be decorated will be injected into the decorator class. @Priority Now we defined the order in which this decorator is to be applied. We do this by setting an interpreter priority. Important note: In CDI 1.1 and below the order of the decorators are 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. A little bit difficult to understand why it is needed in the first place and it goes down to the basic fundamental requirement of OO systems which is to pass a message from one object to another telling the object to do something as a result of a state change on another object but the big difference here verse simply invoking a method on a dependent object is that you care about decoupling in one way or another. Perhaps you have an event for which you want to trigger observers, multiple observers, multiple endpoints that react to that particular endpoint because you want some loose coupling because you want to change which observer actually gets triggered at runtime. This is the original reason you need the observer pattern. The way you implement the observer pattern is sort of antithetical to the original goal of the observer, the GOF way is to implement the interface on a bunch of objects then on the listener you have to register the concrete implementations of each of those instances.  Its a bit self defeating if the goal is to create loosely coupled systems. How does Java EE solve this, it does it in a much more loosely coupled fashion. 
  26. Event We have a stateless bean that is listening for events of type MessageEvent. When it hears such an event it calls messageEvent.fire and give it the payload that the observer is expecting. In this case it is a welcome message. Now all dependents are notified.
  27. The observer has a method with its expected payload which is marked with the Observes annotation, this says: observe for any events that match the payload type of the parameter, in this case a MessageEvent.
  28. You can also use qualifiers here to filter events. For example, you can qualify the Observes annotation by using 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 events 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