Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

jDays Sweden 2016

304 views

Published on

Design Patterns are not only cool but also bring years of collective wisdom to every level of developers. Since GoF, many books have been written and words shed, as well as many new concepts like Enterprise and Domain Design Patterns extended the coverage the Design Patterns, originally shared by the famous Gang of Four. Unlike the J2EE 1.4 era, Java EE provides easy and out of box implementations of many well known design patterns such as Singleton, Façade, Observer, Factory, Dependency Injection, Decorator, Data Access Patterns, MVC and even more. Many classical design patterns are actually just one annotation away from your project.

Published in: Internet
  • Nice !! Download 100 % Free Ebooks, PPts, Study Notes, Novels, etc @ https://www.ThesisScientist.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

jDays Sweden 2016

  1. 1. @alextheedom Java EE revisits design patterns Alex Theedom @alextheedom
  2. 2. @alextheedom Safe Harbour Statement All opinions expressed are my own and not endorsed by any company or entity.
  3. 3. @alextheedom Who am I? Alex Theedom, Senior Java Developer @alextheedom
  4. 4. @alextheedom Available at
  5. 5. @alextheedom What’s on? • Design patterns retrospective • Map classical design patterns to Java EE 7 • Contexts and Dependency Injection • Singleton, Factory, Façade, Decorator and Observer • Final Conclusions • Q&A
  6. 6. @alextheedom What are you doing? • Java Enterprise Edition (J2EE, EE 6/7) • Spring
  7. 7. @alextheedom 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?
  8. 8. @alextheedom Enterprise Java and design patterns •JavaOne 2000 talk: Prototyping patterns for the J2EE platform •Core J2EE Patterns (D. Anur, J. Crupi and D. Malks) •Out-of-box design pattern implementations with Java EE 5
  9. 9. @alextheedom Java EE Programming Model •Simplifies programming model •Annotations have replaced XML description files •Convention over Configuration •CDI hides object creation •Resources are injected by type •@Inject and disambiguation via custom qualifier •POJO (JSR 299 managed bean) •Otherwise @Produces
  10. 10. @alextheedom Singleton Pattern •Creational pattern •Single instance and instantiated once •Must be thread safe •Not normally destroy during application life cycle •Classic implementation: private constructor, double locking, static initializer, enums …
  11. 11. @alextheedom Singleton Pattern @DependsOn("DatabaseConnectionBean") @Startup @Singleton public class Logger { @PostConstruct void constructExpensiveObject() { // Expensive construction } } @DependsOn("DatabaseConnectionBean") @Startup @Singleton public class Logger { @PostConstruct void constructExpensiveObject() { // Expensive construction } } @Inject Logger logger; @Inject Logger logger;
  12. 12. @alextheedom Singleton Pattern •Conclusions so far •Very different implementation •Substantially less boilerplate code •Enhancements via specialized annotations There’s more…
  13. 13. @alextheedom Singleton Pattern @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class Logger { @AccessTimeout(value = 30, unit=TimeUnit.SECONDS) @Lock(LockType.WRITE) public void addMessage(String message) {} @Lock(LockType.READ) public String getMessage() {} } @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class Logger { @AccessTimeout(value = 30, unit=TimeUnit.SECONDS) @Lock(LockType.WRITE) public void addMessage(String message) {} @Lock(LockType.READ) public String getMessage() {} } •Container/bean managed concurrency
  14. 14. @alextheedom The Good, Bad and the Ugly •The Good: •enhancements via specialized annotations •startup behavioural characteristics •fine grain control over concurrency and access timeout •substantially less boilerplate code
  15. 15. @alextheedom The Good, Bad and the Ugly •The Bad: •overuse can cause problems •lazy loading causes delays •eager loading causes memory problems
  16. 16. @alextheedom •And the ugly: •considered an anti-pattern •only niche use •smarter to use a stateless session bean The Good, Bad and the Ugly
  17. 17. @alextheedom Factory Pattern •Creational pattern •Interface for creating family of objects •Clients are decoupled from the creation
  18. 18. @alextheedom 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;
  19. 19. @alextheedom Factory Pattern •Problem! Multiple concrete implementations public class CoffeeMachine implements DrinksMachine { // Implementation code } public class SoftDrinksMachine implements DrinksMachine { // Implementation code } public class CoffeeMachine implements DrinksMachine { // Implementation code } public class SoftDrinksMachine implements DrinksMachine { // Implementation code } @Inject DrinksMachine drinksMachine; @Inject DrinksMachine drinksMachine; •Which DrinksMachine to inject? ?!?
  20. 20. @alextheedom Factory Pattern •Solution! Qualifiers @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface SoftDrink @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface SoftDrink @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface Coffee @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface Coffee
  21. 21. @alextheedom Factory Pattern •Annotate respective classes @Coffee public class CoffeeMachine implements DrinksMachine { // Implementation code } @Coffee public class CoffeeMachine implements DrinksMachine { // Implementation code } @SoftDrink public class SoftDrinksMachine implements DrinksMachine { // Implementation code } @SoftDrink public class SoftDrinksMachine implements DrinksMachine { // Implementation code }
  22. 22. @alextheedom Factory Pattern •Annotate injection points @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @SoftDrink DrinksMachine softDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine; @Inject @Coffee DrinksMachine coffeeDrinksMachine;
  23. 23. @alextheedom Factory Pattern •Remember •Only JSR299 beans are ‘injectable’ •But I want to inject a Collection type or Object with a parameterized constructor -> let’s dive deeper
  24. 24. @alextheedom 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;
  25. 25. @alextheedom Factory Pattern •Scope •Determines when method called •Life of object: @RequestScoped -> @ApplicationScoped @RequestScoped @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @RequestScoped @History @Produces public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; }
  26. 26. @alextheedom The Good, Bad and the Ugly •The Good: •easy to implement •no boilerplate code •works magically •any object can be made injectable •automatic per class configuration •Disambiguation/filtration via qualifiers
  27. 27. @alextheedom The Good, Bad and the Ugly •The Bad: named annotation is not type safe @Named("History") -> @History •and the ugly: object creation hidden, hard to follow execution flow, IDE should help
  28. 28. @alextheedom Façade Pattern •Hides the complex logic and provides the interface for the client •Typically used in APIs •Classic implementation: Just create a method to hide complexity
  29. 29. @alextheedom 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;
  30. 30. @alextheedom The Good, Bad and the Ugly •The Good: simple, robust, gives you a range of services •The Bad: over use introduces unnecessary layers, if you don’t need it don’t introduce one •and the ugly: there isn’t one really
  31. 31. @alextheedom Decorator Pattern •Structural Pattern •Dynamically adds logic to an object at runtime •More flexible that inheritance •Classic implementation: Both the decorator and target object share the same interface. Decorator wraps the target object and adds its own behaviour
  32. 32. @alextheedom Decorator Pattern @Decorator @Priority(Interceptor.Priority.APPLICATION) public class PriceDiscountDecorator implements Product { @Coffee @Any @Delegate @Inject private Product product; public String generateLabel() { product.setPrice(product.getPrice() * 0.5); return product.generateLabel(); } } @Decorator @Priority(Interceptor.Priority.APPLICATION) public class PriceDiscountDecorator implements Product { @Coffee @Any @Delegate @Inject private Product product; public String generateLabel() { product.setPrice(product.getPrice() * 0.5); return product.generateLabel(); } }
  33. 33. @alextheedom •The Good: very easy to change behaviour without breaking legacy code •The Bad: needs XML config (<CDI 1.1) •and the ugly: overuse will introduce an execution flow which is hard to follow The Good, Bad and the Ugly
  34. 34. @alextheedom Observer Pattern •Behavioural Pattern •Publisher-Subscriber •Classic implementation: Implement a Subscriber interface, register with publisher and call a notify method on subscribers
  35. 35. @alextheedom Observer Pattern •Notifies dependents of state change @Stateless public class PublishService { @Inject Event<String> event; public void producer(){ event.fire("Take me to your leader"); } } @Stateless public class PublishService { @Inject Event<String> event; public void producer(){ event.fire("Take me to your leader"); } }
  36. 36. @alextheedom Observer Pattern •Dependent receives state change notification @Stateless public class MessageObserver { public void trace(@Observes String message){ System.out.println(message); } } @Stateless public class MessageObserver { public void trace(@Observes String message){ System.out.println(message); } }
  37. 37. @alextheedom Observer Pattern •Qualifier to filter events @WarningMessage @Inject Event<String> event; @WarningMessage @Inject Event<String> event; public void trace(@Observes @WarningMessage String message)public void trace(@Observes @WarningMessage String message)
  38. 38. @alextheedom 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. 39. @alextheedom Entity •Lightweight domain object which is persistable •Annotated with javax.persistence.Entity •Can represent relational data object/relational mapping annotations
  40. 40. @alextheedom Entity @Entity public class Contact { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; } @Entity public class Contact { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; }
  41. 41. @alextheedom Final Conclusion •Efficiency savings •Greater control over behaviour •New features enhance implementation
  42. 42. @alextheedom Q & A
  43. 43. @alextheedom Java EE revisits design patterns Alex Theedom @alextheedom Thank you

×