KEMBAR78
Java EE Revisits GoF Design Patterns | PDF
Java EE revisits
Design Patterns
Reza Rahman @reza_rahman
Murat Yener @yenerm
Who we are?
Reza Rahman, Java Evangelist
@reza_rahman
reza.rahman@oracle.com
Murat Yener, Mobile Dev, Java EE enthusiast
@yenerm
murat@muratyener.com
40%
discount with promo
code
VBK43
when ordering
through
wiley.com
valid until end of
December 2015
the beginning
Dijkstra: Object-oriented programming is an
exceptionally bad idea which could only have
originated in California
Design patterns are "descriptions of communicating
objects and classes that are customized to solve a
general design problem in a particular context."
Gang of Four
Enterprise Java and
Design Patterns
• JavaOne 2000 talk (TS-1341) Prototyping patterns
for the J2EE Platform
• Core J2EE Design Patterns (Deepak Alur, John
Crupi and Dan Malks)
• Out-of-box DP implementations with Java EE 5
Singleton
• “Ensure a class has only one instance, and provide
a global point of access to it
• Classic implementation: private constructor, double
locking, static initializer, enums…
• must be thread safe!!
Singleton in Java EE
public class SingletonBean {
}
Singleton in Java EE
@Singleton
public class SingletonBean {
}
Singleton in Java EE
@Singleton
public class SingletonBean {
@PostConstruct
void startUpTask() {
// Perform start up tasks
}
}
Singleton in Java EE
@Startup
@Singleton
public class SingletonBean {
@PostConstruct
void startUpTask() {
// Perform start up tasks
}
}
Singleton (cont.)
• Simple
• No XML configuration needed
• Simple inject to use beans
@Inject SingletonBean bean;
pros & cons
• The Good: expensive objects, caching, global
access…
• The Bad: overuse can cause problems, lazy loading
can cause delays, not lazy loading may cause
memory problems
• and the ugly: considered as an anti-pattern
Abstract Factory
• Creational pattern, to encapsulate creation
• Only the part responsible for creation changes
Abstract Factory in Java EE
public class HelloProducer {
public String getMessage(){
return "Hello World";
}
}
private String message;
Abstract Factory in Java EE
public class HelloProducer {
@Produces
public String getMessage(){
return "Hello World";
}
}
@Inject
private String message;
Abstract Factory in Java EE
public class HelloProducer {
@Produces
public String getMessage(){
return "Hello World";
}
@Produces
public String getGreeting(){
return "Greetings Earthlings";
}
}
@Inject
private String message; ?!?
Abstract Factory in Java EE
public class HelloProducer {
@Produces @Named(“Message")
public String getMessage(){
return "Hello World";
}
@Produces @Named(“Greeting")
public String getGreeting(){
return "Greetings Earthlings";
}
}
@Inject @Named(“Message")
private String message;
pros & cons
• The Good: easy to implement, no boilerplate, works
magically
• The Bad: named annotation is not type safe so
same type of objects better be wrapped or
annotated with qualifiers
• and the ugly: may introduce hard to understand
flow
Facade in Java EE
• Hides the complex logic and provides an interface
for the clients
• Typically used in APIs
• Classic implementation: Just create a method to
hide complexity
Facade in Java EE
public class HelloFacade {
public String executeBusinessLogic(){
//very very complex logic
}
}
private HelloFacade service;
Facade in Java EE
@Stateless
public class HelloFacade {
public String executeBusinessLogic(){
//very very complex logic
}
}
@Inject
private HelloFacade service;
pros & cons
• The Good: stateless or stateful, easy to implement.
Can be exposed as rest or web service endpoint.
• The Bad: overuse may introduce unnecessary
layers
• and the ugly: the name of the pattern :)
Decorator in Java EE
• Adds behavior to objects in runtime.
• More flexible and extensible than inheritance
• Classic implementation: Both the decorator and
target object shares the same interface. Decorator
holds wraps the target object and adds its own
behavior.
Decorator in Java EE
public class ConfigDecorator implements Accessory
{

@Inject 

private Accessory product;



public Long getPrice() {

return getPrice()+1000;

}


}
Decorator in Java EE
@Decorator
public class ConfigDecorator implements Accessory
{

@Inject
@Delegate

private Accessory product;



public Long getPrice() {

return getPrice()+1000;

}


}
Decorator in Java EE
<decorators>
<class>com.patterns.ConfigDecorator</class>
</decorators>
Decorator in Java EE
<decorators>
<class>com.patterns.ConfigDecorator</class>
<class>com.patterns.AnotherDecorator</class>
</decorators>
pros & cons
• The Good: unlike inheritance very easy to change
behavior without breaking legacy code.
• The Bad: needs xml configuration (<CDI 1.1)
• and the ugly: overuse will introduce an execution
flow which is hard to follow
Observer in Java EE
• Don’t call us, we call you!
• Publisher-Subscriber
• Classic implementation: Out-of-box implementation!
Observable Interface, Listeners via inner classes
Observer in Java EE
@Stateless
public class HelloWorldObserver {
public void traceHelloWorlds(
@Observable String message){
//…
}
}
@Stateless
public class PublishService {
@Inject Event<String> event;
public void producer(){
event.fire(“Hey!!” + message);
}
}
Observer in Java EE
@Stateless
public class HelloWorldObserver {
public void traceHelloWorlds(
@Observable SomeObj message){
//…
}
}
@Stateless
public class PublishService {
@Inject Event<SomeObj> event;
public void producer(){
event.fire(new SomeObj());
}
}
pros & cons
• The Good: very very easy, no boiler plate..
• The Bad: may introduce difficulty to follow execution
flow & debug
• and the ugly: nothing.. it’s beautiful :)
MVC in Java EE
• It is not a pattern but a composite collection of other
patterns
• Is used and accepted as industry standard in
almost all UI frameworks.
• Keeps data, logic and UI code separate and easy
to change
• JSF is a clean and simple implementation of MVC
The Model
• Represents data and related business logic
• Model is usually a CDI bean
The View
• Visual representation of Data
• User interacts with View to access data and trigger
business logic
The Controller
• Links view with model
• Directs application flow
MVC in Java EE
• Model: Backing beans which are annotated POJOs
with @Named and @RequestScope
• View: Facelets which are written in XHTML with CSS
• Controller: FacesServlet
Entity
• Lightweight domain object which is persistable
• Annotated with javax.persistance.Entity
• Can represent relational data object/relational
mapping annotations
Entity
@Entity
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
protected String firstName;
protected String lastName;
}
DAO
• Used for accessing the persistent data storage
• Usually singleton
• Simples cases entity manager is the DAO
• Complex cases you create DAOs for entity objects
• Usually a CDI managed bean
DAO
@PersistenceContext
EntityManager em;
//…
SomeObject obj = em.find(SomeObject.class, id);
em.persist(obj);
em.merge(obj);
DTO
• Serializable object to transfer data between layers
• simple cases entity is DTO
• often annotated via JAXB and JSON processing
Java API.
DTO
@Entity
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
protected String firstName;
protected String lastName;
}
DTO
@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@XmlTransient
private Long id;
protected String firstName;
protected String lastName;
}
Domain Driven Design
</slides>
Reza Rahman
@reza_rahman
reza.rahman@oracle.com
Murat Yener
@yenerm
murat@muratyener.com

Java EE Revisits GoF Design Patterns

  • 1.
    Java EE revisits DesignPatterns Reza Rahman @reza_rahman Murat Yener @yenerm
  • 2.
    Who we are? RezaRahman, Java Evangelist @reza_rahman reza.rahman@oracle.com Murat Yener, Mobile Dev, Java EE enthusiast @yenerm murat@muratyener.com
  • 3.
    40% discount with promo code VBK43 whenordering through wiley.com valid until end of December 2015
  • 4.
    the beginning Dijkstra: Object-orientedprogramming is an exceptionally bad idea which could only have originated in California Design patterns are "descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context." Gang of Four
  • 5.
    Enterprise Java and DesignPatterns • JavaOne 2000 talk (TS-1341) Prototyping patterns for the J2EE Platform • Core J2EE Design Patterns (Deepak Alur, John Crupi and Dan Malks) • Out-of-box DP implementations with Java EE 5
  • 6.
    Singleton • “Ensure aclass has only one instance, and provide a global point of access to it • Classic implementation: private constructor, double locking, static initializer, enums… • must be thread safe!!
  • 7.
    Singleton in JavaEE public class SingletonBean { }
  • 8.
    Singleton in JavaEE @Singleton public class SingletonBean { }
  • 9.
    Singleton in JavaEE @Singleton public class SingletonBean { @PostConstruct void startUpTask() { // Perform start up tasks } }
  • 10.
    Singleton in JavaEE @Startup @Singleton public class SingletonBean { @PostConstruct void startUpTask() { // Perform start up tasks } }
  • 11.
    Singleton (cont.) • Simple •No XML configuration needed • Simple inject to use beans @Inject SingletonBean bean;
  • 12.
    pros & cons •The Good: expensive objects, caching, global access… • The Bad: overuse can cause problems, lazy loading can cause delays, not lazy loading may cause memory problems • and the ugly: considered as an anti-pattern
  • 13.
    Abstract Factory • Creationalpattern, to encapsulate creation • Only the part responsible for creation changes
  • 14.
    Abstract Factory inJava EE public class HelloProducer { public String getMessage(){ return "Hello World"; } } private String message;
  • 15.
    Abstract Factory inJava EE public class HelloProducer { @Produces public String getMessage(){ return "Hello World"; } } @Inject private String message;
  • 16.
    Abstract Factory inJava EE public class HelloProducer { @Produces public String getMessage(){ return "Hello World"; } @Produces public String getGreeting(){ return "Greetings Earthlings"; } } @Inject private String message; ?!?
  • 17.
    Abstract Factory inJava EE public class HelloProducer { @Produces @Named(“Message") public String getMessage(){ return "Hello World"; } @Produces @Named(“Greeting") public String getGreeting(){ return "Greetings Earthlings"; } } @Inject @Named(“Message") private String message;
  • 18.
    pros & cons •The Good: easy to implement, no boilerplate, works magically • The Bad: named annotation is not type safe so same type of objects better be wrapped or annotated with qualifiers • and the ugly: may introduce hard to understand flow
  • 19.
    Facade in JavaEE • Hides the complex logic and provides an interface for the clients • Typically used in APIs • Classic implementation: Just create a method to hide complexity
  • 20.
    Facade in JavaEE public class HelloFacade { public String executeBusinessLogic(){ //very very complex logic } } private HelloFacade service;
  • 21.
    Facade in JavaEE @Stateless public class HelloFacade { public String executeBusinessLogic(){ //very very complex logic } } @Inject private HelloFacade service;
  • 22.
    pros & cons •The Good: stateless or stateful, easy to implement. Can be exposed as rest or web service endpoint. • The Bad: overuse may introduce unnecessary layers • and the ugly: the name of the pattern :)
  • 23.
    Decorator in JavaEE • Adds behavior to objects in runtime. • More flexible and extensible than inheritance • Classic implementation: Both the decorator and target object shares the same interface. Decorator holds wraps the target object and adds its own behavior.
  • 24.
    Decorator in JavaEE public class ConfigDecorator implements Accessory {
 @Inject 
 private Accessory product;
 
 public Long getPrice() {
 return getPrice()+1000;
 } 
 }
  • 25.
    Decorator in JavaEE @Decorator public class ConfigDecorator implements Accessory {
 @Inject @Delegate
 private Accessory product;
 
 public Long getPrice() {
 return getPrice()+1000;
 } 
 }
  • 26.
    Decorator in JavaEE <decorators> <class>com.patterns.ConfigDecorator</class> </decorators>
  • 27.
    Decorator in JavaEE <decorators> <class>com.patterns.ConfigDecorator</class> <class>com.patterns.AnotherDecorator</class> </decorators>
  • 28.
    pros & cons •The Good: unlike inheritance very easy to change behavior without breaking legacy code. • The Bad: needs xml configuration (<CDI 1.1) • and the ugly: overuse will introduce an execution flow which is hard to follow
  • 29.
    Observer in JavaEE • Don’t call us, we call you! • Publisher-Subscriber • Classic implementation: Out-of-box implementation! Observable Interface, Listeners via inner classes
  • 30.
    Observer in JavaEE @Stateless public class HelloWorldObserver { public void traceHelloWorlds( @Observable String message){ //… } } @Stateless public class PublishService { @Inject Event<String> event; public void producer(){ event.fire(“Hey!!” + message); } }
  • 31.
    Observer in JavaEE @Stateless public class HelloWorldObserver { public void traceHelloWorlds( @Observable SomeObj message){ //… } } @Stateless public class PublishService { @Inject Event<SomeObj> event; public void producer(){ event.fire(new SomeObj()); } }
  • 32.
    pros & cons •The Good: very very easy, no boiler plate.. • The Bad: may introduce difficulty to follow execution flow & debug • and the ugly: nothing.. it’s beautiful :)
  • 33.
    MVC in JavaEE • It is not a pattern but a composite collection of other patterns • Is used and accepted as industry standard in almost all UI frameworks. • Keeps data, logic and UI code separate and easy to change • JSF is a clean and simple implementation of MVC
  • 34.
    The Model • Representsdata and related business logic • Model is usually a CDI bean
  • 35.
    The View • Visualrepresentation of Data • User interacts with View to access data and trigger business logic
  • 36.
    The Controller • Linksview with model • Directs application flow
  • 37.
    MVC in JavaEE • Model: Backing beans which are annotated POJOs with @Named and @RequestScope • View: Facelets which are written in XHTML with CSS • Controller: FacesServlet
  • 38.
    Entity • Lightweight domainobject which is persistable • Annotated with javax.persistance.Entity • Can represent relational data object/relational mapping annotations
  • 39.
    Entity @Entity public class Contact{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; protected String firstName; protected String lastName; }
  • 40.
    DAO • Used foraccessing the persistent data storage • Usually singleton • Simples cases entity manager is the DAO • Complex cases you create DAOs for entity objects • Usually a CDI managed bean
  • 41.
    DAO @PersistenceContext EntityManager em; //… SomeObject obj= em.find(SomeObject.class, id); em.persist(obj); em.merge(obj);
  • 42.
    DTO • Serializable objectto transfer data between layers • simple cases entity is DTO • often annotated via JAXB and JSON processing Java API.
  • 43.
    DTO @Entity public class Contact{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; protected String firstName; protected String lastName; }
  • 44.
    DTO @Entity @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Contact{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @XmlTransient private Long id; protected String firstName; protected String lastName; }
  • 45.
  • 46.