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.

Java EE changes design pattern implementation: JavaDays Kiev 2015

656 views

Published on

The implementation of traditional design patterns have changed in Java EE 7. By taking advantage of Java EE features such as CDI and the smart use of annotations, traditional design patterns can be implemented in a much cleaner and quicker way. With the use of code examples I will demonstrate how to implement some of the most commonly use design patterns in Java EE. Among the design patterns discuss there will be Factory, Singleton, Observer and Decorator.

Published in: Technology
  • Be the first to comment

Java EE changes design pattern implementation: JavaDays Kiev 2015

  1. 1. #JavaEE @alextheedom Java EE revisits design patterns Alex Theedom @alextheedom Java Day Kiev
  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 alex.theedom@gmail.com
  4. 4. @alextheedom 40% discount with promo code VBK43 when ordering through wiley.com valid until end of December 2015 Also available at
  5. 5. @alextheedom What’s on? • Another talk on design patterns!! • Overview design patterns • Context Dependency Injection • Singleton, Factory, Façade, Decorator and Observer • Entity • Conclusion
  6. 6. @alextheedom What are you doing? • Java Enterprise Edition (J2SE, EE) • Spring
  7. 7. @alextheedom The beginning Design patterns are “description of communication objects and classes that are customized to solve a general design problem in a particular context”. Gang of Four 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 Design Patterns (Deepak Anur, John Crupi and Dan Malks) •Out-of-box DP implementations with Java EE 5
  9. 9. @alextheedom Context Dependency Injection •Simplifies programming model •Annotations have replaced XML config files •Convention over Configuration •Resources are injected by type •@Inject and disambiguation via custom qualifier •POJO (JSR 299 managed bean) •Otherwise @Producer
  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("PrimaryBean") @Startup @Singleton public class Logger { @PostConstruct void startUpTask() { // Perform start up tasks } } @DependsOn("PrimaryBean") @Startup @Singleton public class Logger { @PostConstruct void startUpTask() { // Perform start up tasks } } @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 Pros & cons •The Good: •enhancements via specialized annotations •startup behavioural characteristics •fine grain control over concurrency and access timeout •substantially less boilerplate code
  15. 15. @alextheedom Pros & cons •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 Pros & cons
  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’ •Interface reference i.e. List, constructor with parameters
  24. 24. @alextheedom Factory Pattern •Dive deeper •Producer methods •Use it like so: @Produces @Library public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @Produces @Library public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @Inject @Library List<Books> library; @Inject @Library List<Books> library;
  25. 25. @alextheedom Factory Pattern •Scope •Determines when method called •Life of object: @RequestScoped -> @ApplicationScoped @RequestScoped @Produces @Library public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; } @RequestScoped @Produces @Library public List<Book> getLibrary(){ // Generate a List of books called 'library' return library; }
  26. 26. @alextheedom Pros & cons •The Good: easy to implement, no boilerplate code, works magically, any object can be made injectable, Automatic per class configuration •The Bad: named annotation is not type safe •and the ugly: object creation hidden, hard to follow execution flow, IDE should help
  27. 27. @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
  28. 28. @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;
  29. 29. @alextheedom Pros & cons •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. 30. @alextheedom Decorator Pattern •Dynamically adds logic to an object •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. 31. @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(); } }
  32. 32. @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 Pros & cons
  33. 33. @alextheedom Observer Pattern •Publisher-Subscriber •Classic implementation: Out-of-box implementation! •Observable interface. Listener via inner classes
  34. 34. @alextheedom Observer Pattern •Notifies dependents of state change @Stateless public class PublishService { @Inject Event<String> event; public void producer(){ event.fire("Hello Kiev"); } } @Stateless public class PublishService { @Inject Event<String> event; public void producer(){ event.fire("Hello Kiev"); } }
  35. 35. @alextheedom Observer Pattern •Dependent receives state change notification @Stateless public class HelloWorldObserver { public void trace(@Observes String message){ // Response to event } } @Stateless public class HelloWorldObserver { public void trace(@Observes String message){ // Response to event } }
  36. 36. @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)
  37. 37. @alextheedom Pros & cons •The Good: very easy, no boilerplate code, less than JMS, the container does the heavy lifting, light weight •The Bad: confusing execution order •and the ugly: nothing, its beautiful
  38. 38. @alextheedom Entity •Lightweight domain object which is persistable •Annotated with javax.persistence.Entity •Can represent relational data object/relational mapping annotations
  39. 39. @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; }
  40. 40. @alextheedom Final Conclusion •Efficiency savings •Greater control over behaviour •New features enhance implementation
  41. 41. @alextheedom Q & A
  42. 42. #JavaEE @alextheedom Java EE revisits design patterns Alex Theedom @alextheedom Kiev 6th - 7th November 2015 Thank you

×