Some of the best practices to follow in Hibernate are:
- Always check the primary key field access, if it’s generated at the database layer then you should not have a setter for this.
- By default hibernate set the field values directly, without using setters. So if you want hibernate to use setters, then make sure proper access is defined as
@Access(value=AccessType.PROPERTY). - If access type is property, make sure annotations are used with getter methods and not setter methods. Avoid mixing of using annotations on both filed and getter methods.
- Use native sql query only when it can’t be done using HQL, such as using database specific feature.
- If you have to sort the collection, use ordered list rather than sorting it using Collection API.
- Use named queries wisely, keep it at a single place for easy debugging. Use them for commonly used queries only. For entity specific query, you can keep them in the entity bean itself.
- For web applications, always try to use JNDI DataSource rather than configuring to create connection in hibernate.
- Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One-to-Many and Many-to-One relationships.
- For collections, try to use Lists, maps and sets. Avoid array because you don’t get benefit of lazy loading.
- Do not treat exceptions as recoverable, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that in-memory state accurately represents the persistent state.
- Prefer DAO pattern for exposing the different methods that can be used with entity bean
- Prefer lazy fetching for associations
Thursday, May 28, 2015
What are best practices to follow with Hibernate framework?
Which design patterns are used in Hibernate framework?
Some of the design patterns used in Hibernate Framework are:
- Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
- Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
- Proxy Pattern – for lazy loading
- Factory pattern – in Session Factory
Struts Framework uses Design Patterns
Every Struts application is used to use certain design patterns whether you now or not, Commonly used Command patterns is also used in Struts when we hit a request and request goes to action-servlet which eventually used Command design pattern to decide further, when we are creating ACTION class we are eventually using Adapter Design pattern.
Moreover, Every Struts application eventually using following design patterns:
Now Lets learn about each in details to know how exactly struts using these design patterns.
Front Controller Design Patterns
- Actually, Struts is one of the fancy example for using a Front Controller pattern, the basic idea of the Front Controller pattern is that a single component handling the input and out put controller, normally a Servlet used to work as Front Controller in design pattern as in Struts ActionServlet and RequestProcessor(Used to handle HTTPRequests) which acts as single control point for the presentation tier in any web application. With the Front Controller pattern, all of the app's requests go through a single controller, which handles dispatching the request to the appropriate places.
To be concise, RequestProcessor class in Struts is responsible for implementing the FRONT CONTROLLER DESIGN, and you can enhance/extend your RequestProcessor by you own read more for What is RequestProcessor, and how to extend it?
Composite View Design Patterns
- Composite Design Pattern is all about re-using the component to standardize the GUI of any webapplication or reduce the effort of change by means of changing at one place changed all over.
Moreover, Every Struts application eventually using following design patterns:
- Front Controller Design Patterns
- Composite View Design Patterns
- Adapter Design Patterns
- Command Design Patterns
- Model -View-Controller Design Patterns
- Inversion of Control(Struts2 HTTPServletRequest through ServletRequestAware)
- Template Method Design Pattern
Now Lets learn about each in details to know how exactly struts using these design patterns.
Front Controller Design Patterns
- Actually, Struts is one of the fancy example for using a Front Controller pattern, the basic idea of the Front Controller pattern is that a single component handling the input and out put controller, normally a Servlet used to work as Front Controller in design pattern as in Struts ActionServlet and RequestProcessor(Used to handle HTTPRequests) which acts as single control point for the presentation tier in any web application. With the Front Controller pattern, all of the app's requests go through a single controller, which handles dispatching the request to the appropriate places.
To be concise, RequestProcessor class in Struts is responsible for implementing the FRONT CONTROLLER DESIGN, and you can enhance/extend your RequestProcessor by you own read more for What is RequestProcessor, and how to extend it?
Composite View Design Patterns
- Composite Design Pattern is all about re-using the component to standardize the GUI of any webapplication or reduce the effort of change by means of changing at one place changed all over.
Design Patterns being used in Spring framework
Design Patterns being used in Spring framework
Spring Design Patterns
1. MVC - The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers.
2. Front controller - Spring provides "DispatcherServlet" to ensure an incoming request gets dispatched to your controllers.
3. View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.
4. Singleton - Beans defined in spring config files are singletons by default.
5. Prototype - Instance type can be prototype.
6. Factory - Used for loading beans through BeanFactory and Application context.
7. Builder - Spring provides programmatic means of constructing BeanDefinitions using the builder pattern through Class "BeanDefinitionBuilder".
8. Template - Used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate.
9. Proxy - Used in AOP & Remoting.
10. DI/IOC - It is central to the whole BeanFactory/ApplicationContext stuff.
Thursday, May 21, 2015
Design patterns used in Frameworks
What design patterns are used in Struts?
Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use theadapter design pattern. The
process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
· Service to Worker
· Dispatcher View
· Composite View (Struts Tiles)
· Front Controller
· View Helper
· Synchronizer Token
Struts controller uses the Command design pattern and the action classes use the Adapter design pattern. The process() method of the RequestProcessor uses the Template method design pattern. Struts also implement the following J2EE design patterns.
* Service to Worker
* Dispatcher View
* Composite View (Struts Tiles)
* Front Controller
* View Helper
* Synchronizer Token
* Service to Worker
* Dispatcher View
* Composite View (Struts Tiles)
* Front Controller
* View Helper
* Synchronizer Token
In current industry trend, it is surprisingly noticed that, people mix up with design patterns and framework. Whwneve somebody design something, it is a trend to brand it as a different patterns. However GOF patterns are fundamental and most of the patterns are derivative of GOF patterns.
e.g.
a)Algorithms are derived mostly using a variation of Strategy or Visitor
b)Actions are Command
c)Implementations are kind of Bridge
d)Request, Response are based on Observer
e)Interactions between the objects are handled by Mediator
f)Object Creational Patterns are: Factory, Abstract Factory, Prototype
g)Structue: Builder
h)Traversal Algorithm: Iterator
i)Object Interface: Adapter
j)Object Behavior: Decorator, State
Successful patterns are product of successfull use of all these GOF patterns.
e.g.
a)Algorithms are derived mostly using a variation of Strategy or Visitor
b)Actions are Command
c)Implementations are kind of Bridge
d)Request, Response are based on Observer
e)Interactions between the objects are handled by Mediator
f)Object Creational Patterns are: Factory, Abstract Factory, Prototype
g)Structue: Builder
h)Traversal Algorithm: Iterator
i)Object Interface: Adapter
j)Object Behavior: Decorator, State
Successful patterns are product of successfull use of all these GOF patterns.
Struts2 is based on WebWork which has IoC. Struts2 supports interface injection (IOC).
Struts follows MVC architecture and uses Front Controller design pattern.
Which version of Struts are you using?
Struts 2 uses Inversion of Control (IoC) pattern also known as dependency injection.
Which version of Struts are you using?
Struts 2 uses Inversion of Control (IoC) pattern also known as dependency injection.
In Struts 2 action class the HTTPServletRequest object can be obtained using IoC pattern
1. public class MyAction implements ServletRequestAware {
2. private HttpServletRequest servletRequest;
3. public void setServletRequest(HttpServletRequest request) {
4. this.servletRequest = request;
5. }
6. }
Yes Spring uses IoC pattern. Strus2 also uses Ioc pattern. I am not sure about Struts 1.x
Struts1.0 follows MVC architecture and Struts 1.1 follows MVC2 architecture which is designed using Front Controller Design Pattern .. The Struts Action classes and their associated action mappings are like the Command pattern. Also, the Form Beans that encapsulate the values entered on a form, these are like a Context Object.
Although struts follows front-controller design,it incorporates an enhanced version of MVC/Model-2 architecture what we call as MVC-CC ie MVC-Configurable Controller.Struts doesn't restrict any design limitations,rather it provides extensibility of implementing any pattern along with it.Controller components and collaborating classes can be customized to meet desired results.
Factory pattern is also used for loading beans through BeanFactory and Application context
The DI thing actually is some kind of strategy pattern. Whenever you want to be some logic/implementation exchangeable you typically find an interface and an appropriate setter method on the host class to wire your custom implementation of that interface.
Spring is a collection of best-practise API patterns, you can write up a shopping list of them as long as your arm. The way that the API is designed encourages you (but doesn't force you) to follow these patterns, and half the time you follow them without knowing you are doing so.
And of course dependency injection, or IoC (inversion of control), which is central to the whole BeanFactory/ApplicationContext stuff.
Some obvious patterns in use in MVC:
Model View Controller :-) . The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a logical view name, and the view selection is left to a separateViewResolver. This makes it easier to reuse controllers for different view technologies.
Front Controller. Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.
View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.
There are loads of different design patterns used, but there are a few obvious ones:
Singleton - beans defined in spring config files are singletons by default.
Template method - used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate,JmsTemplate, JpaTemplate.
Both in Struts and spring framework
Table 1. Summary of MVC components
| ||
Purpose
|
Description
| |
Model
|
Maintain data
|
Business logic plus one or more data sources such as a relational database
|
View
|
Display all or a portion of the data
|
The user interface that displays information about the model to the user
|
Controller
|
Handle events that affect the model or view
|
The flow-control mechanism means by which the user interacts with the application
|
Guidelines for using Model 1 or Model 2
| ||
Criterion
|
Model 1
|
Model 2
|
Type of Web application
|
Simple
|
Complex
|
Nature of developer's task
|
Quick prototyping
|
Creating an application to be modified and maintained
|
Who is doing the work
|
View and controller being done by the same team
|
View and controller being done by different teams
|
Insight about the design patterns used in JSF framework, and how they work in-depth. (I.e. how it functions within the JSF framework)
The JSF framework leverages following design patterns
- Singleton
- Model-View-Controller
- Factory Method
- State
- Composite
- Decorator
- Strategy
- Template Method
- Observer
It's a robust framework in that its architecture is based on already proven design patterns, which are utilized very nicely in the JSF framework.
Patterns: - The use patterns are a ubiquitous way to abstract a problem and its solutions. Because patterns are recognized by all developers and architects, patterns can save time and energy. In layman's terms, a pattern is a proven solution to a well-known problem. You can reuse patterns, and this reuse helps solutions become robust.
The intent of the Singleton pattern is to ensure that only one instance of a class is loaded, and that the instance provides a global point of access. While starting a Web application that has JSF support, the Web container initializes a FacesServlet instance. In this stage, FacesServlet instantiates the Application and LifeCycle instances once per Web application. These instances represent the well-known Singleton pattern, which typically requires only one instance of the type.
A Web application using JSF requires only one instance of the Application and LifeCycle classes. LifeCycle manages the entire life cycle of multiple JSF requests. It makes sense to have these objects as Singleton patterns because their states and behaviors are shared across all requests. LifeCycle maintains PhaseListeners, which are also Singleton patterns. PhaseListeners are shared by all JSF requests. You can use a Singleton pattern extensively in JSF framework to reduce the memory footprint and provide global access to objects. NavigationHandler(used to determine logical outcome of the request) and ViewHandler (used to create view) also represent Singleton patterns.
Example:
The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, “The President of the United States” is a global point of access that identifies the person in the office.
The MVC pattern's purpose is to decouple Model (or data) from the presentation of the data (View). If your application has more than one presentation, you can replace only the view layer and reuse code for the controller and model. Similarly, if you need to change a model, the view layer remains largely unaffected. Controller handles user actions that might result in changes in the model and updates to the views. When a user requests a JSF page, the request goes to FacesServlet. FacesServlet is the front controller servlet used in JSF. Like many other Web application frameworks, JSF uses the MVC pattern to decouple the view and the model. To handle user requests centrally, the controller servlet makes changes to the model and navigates users to views.
FacesServlet is the controller element in the JSF framework which all user requests go through. FacesServlet examines user requests and calls various actions on the model using managed beans. Backing, or managed, beans are an example of the model. JSF user interface (UI) components represent the view layer. The MVC pattern helps to divide tasks among developers who have different skill sets so tasks can becarried out in parallel; that is, GUI designers can create JSF pages with rich UI components while back-end developers can create managed beans to write business-logic specific code.
The purpose of the Factory Method pattern is to define an interface for creating an object but deferring instantiation of the object to subclasses. In the JSF architecture, the Factory Method pattern is used to create objects. LifeCycleFactory is a factory object that creates and returns LifeCycle instances. The getLifeCycle (String LifeCycleId) method of LifeCycleFactory is a Factory Method pattern that creates (if needed) and returns LifeCycle instances based on LifeCycleId. Custom JSF implementation can redefine an abstract getLifeCycle method to create a custom LifeCycle instance. Default JSF implementation gives the default LifeCycle instance. Also, for every JSF request, FacesServlet gets FacesContext from FacesContextFactory. FacesContextFactory is an abstract class that exposes the getFacesContext API, and JSF implementation provides concrete implementation of the FacesContextFactory and getFacesContext API. This is another example of the Factory Method pattern where concrete FacesContextFactory creates FacesContext objects.
Example:
Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the mold
The intent of the State pattern is to distribute state-specific logic across different classes that represent states. FacesServlet invokes execute and render methods on a LifeCycle instance. LifeCycle collaborates with different Phases in order to execute a JSF request. JSF implementation follows the State pattern here. If this pattern wasn't used, LifeCycle implementation would be cluttered with a lot of conditionals (or "if" statements). JSF implementation creates separate classes of each state (or phase) and invokes steps. A phase is an abstract class that defines the common interface for every step. In the JSF framework, six phases, or steps, are defined: RestoreViewPhase, ApplyRequestValues, ProcessValidationsPhase, UpdateModelValuesPhase, InvokeApplicationPhase, and RenderResponsePhase.
As in the State pattern, LifeCycle passes a FacesContext object to the phases. Each phase or state changes the contextual information passed to it and then sets the flag in the FacesContext itself to indicate the next possible step. JSF implementation alters its behavior with each step. Each phase can be responsible for the next phase. FacesContext has two flags -- renderResponse and responseComplete -- to change the sequence of execution. After execution of each step, LifeCycle checks whether either of these flags was set by the previous phase. If a responseComplete is set, LifeCycle abandons the execution of the request altogether. If a renderResponse flag is set after some phase, JSF implementation skips remaining phases and goes directly to the render response phase. If neither flag is set, LifeCycle executes the next step in the sequence.
Example:
Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.
The Composite pattern allows clients to deal with composite and primitive objects uniformly. A composite object is a container for primitive objects. In the first phase (Restore View phase) and the last phase (Render Response phase), the UI View is constructed using JSF UI components. UIComponentBase represents an abstract Component class in the Composite pattern. UIViewRoot is the Composite class, andUIOutput, for example, is the leaf (or primitive). The UIComponentBase class defines common methods for leaf and composite objects, such as encoding and decoding values and child management functions. Child management functions, such as getChildren, return an empty list for leaf nodes and children for composite nodes.
Example
The Composite composes objects into tree structures and lets clients treat individual objects and compositions uniformly. Although the example is abstract, arithmetic expressions are Composites. An arithmetic expression consists of an operand, an operator (+ - * /), and another operand. The operand can be a number, or another arithmetic expression. Thus, 2 + 3 and (2 + 3) + (4 * 6) are both valid expressions.
A component has many elements and itself which has many elements and itself, etc. A file system is a typical example. Directory is a composite pattern. When you deal with Directory object, if isFile() returns true, work on file, if isDirectory() returns true, work on Directory object.
General Manager may have several employees and some of employees are Managers which have several employees.
· Menus that contain menu items, each of which could be a menu.
· Row-column GUI layout managers that contain widgets, each of which could be a row-column GUI layout manager.
· Directories that contain files, each of which could be a directory.
· Containers that contain Elements, each of which could be a Container.
The intent of the Decorator pattern is to extend the behavior of an object dynamically without subclassing. The JSF framework has many extension points, or pluggability mechanisms. JSF implementation can replace default PropertyResolver, VariableResolver, ActionListener, NavigationHandler, ViewHandler, or StateManager by using the Decorator pattern. Typically custom implementation receives the reference to the default implementation passed through its constructor. Custom implementation overrides only a subset of the functionality and delegates the rest of the functions to the default implementation. If you want to implement a custom ViewHandler that overrides the calculateLocale method from the default ViewHandler implementation, you can write
CustomViewHandler class as in Listing 1: Listing 1. CustomViewHandler snippet
public class CustomViewHandler extends ViewHandler {
public CustomViewHandler(ViewHandler handler) {
super();
oldViewHandler = handler;
}
private ViewHandler oldViewHandler = null;
public void renderView (facesContext context, UIViewRoot view) {
//delegate method to oldViewHandler
oldViewHandler.renderView(context, view);
}
//custom implementation of calculateLocale
public Locale calculateLocale(FacesContext context) {
}
}
|
Examples:
You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.
The Decorator attaches additional responsibilities to an object dynamically. The ornaments that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes, glass ornaments, etc., can be added to a tree to give it a festive look. The ornaments do not change the tree itself which is recognizable as a Christmas tree regardless of particular ornaments used. As an example of additional functionality, the addition of lights allows one to “light up” a Christmas tree.
Although paintings can be hung on a wall with or without frames, frames are often added, and it is the frame which is actually hung on the wall. Prior to hanging, the paintings may be matted and framed, with the painting, matting, and frame forming a single visual component.
Although paintings can be hung on a wall with or without frames, frames are often added, and it is the frame which is actually hung on the wall. Prior to hanging, the paintings may be matted and framed, with the painting, matting, and frame forming a single visual component.
Conclusion: This is a pattern that provides quite a bit of flexibility. It eliminates the needs for sub-classing. It is a pattern that is pretty effective when the object being used should appear to change its behavior
Dynamic languages
Dynamic languages
The decorator pattern can also be implemented in dynamic languages with neither interfaces nor traditional OOP inheritance.
The purpose of the Strategy pattern is to encapsulate a concept that varies. The JSF framework employs the Strategy pattern for rendering UI components using the delegated implementation model. JSF technology supports two kinds of rendering models. In a direct implementation model, UI components decode the values from the incoming request themselves and encode the values to be displayed. In a delegated implementation model, decoding and encoding operations are delegated to the separate renderer associated with the component. The latter model is more flexible than direct implementation and leverages the Strategy design pattern. In the Strategy pattern, you encapsulate an algorithm that varies into a separate object so the algorithm can be varied dynamically. JSF implementation might register additional renderers with the existing renderkit instance, and, at application startup time, JSF implementation reads the configuration file and associates those renderers to the UI components.
Example:-
A Strategy defines a set of algorithms that can be used interchangeably. Modes of transportation to an airport is an example of a Strategy. Several options exist such as driving one’s own car, taking a taxi, an airport shuttle, a city bus, or a limousine service. For some airports, subways and helicopters are also available as a mode of transportation to the airport. Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based on tradeoffs between cost, convenience, and time.
Compress files using different algorithms or save files in different formats or draw graphic in different presentations
The Template Method pattern's intention is to defer variant steps to the subclasses while the parent class defines invariant steps of the algorithm. The JSF framework offers functionality provided by the Template Method pattern through PhaseListeners. Template Method (or "hook") is implemented so Web authors can provide implementation for the optional steps between phases while main phases remain the same as defined by the JSF framework. The JSF framework provides PhaseListeners that are conceptually similar to variant steps of the Template Method pattern. The JSF framework has six predefined phases, and between each phase, a Web author can implement PhaseListeners to provide hooks similar to the Template Method hooks. In fact, this is much more extensible than the Template Method pattern. You can provide hooks after each phase by registering a PhaseListener that has PhaseId of ANY_PHASE value. If the PhaseId is ANY_PHASE, the JSF implementation calls the PhaseListener before and after every phase. The implementation is slightly different in the JSF framework because one can have no PhaseListeners at all, but in the Template Method pattern, subclasses generally redefine variant steps that are left abstract in the parent class.
Intent
· Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
· Base class declares algorithm ‘placeholders’, and derived classes implement the placeholders.
ExampleThe Template Method defines a skeleton of an algorithm in an operation, and defers some steps to subclasses. Home builders use the Template Method when developing a new subdivision. A typical subdivision consists of a limited number of floor plans with different variations available for each. Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models.
· check client's bank balance history
· check client's credit score from three different companies
· check client's other loan information
· check client's stock holding value
· check client's income potential in the future
· etc.
You may use a template method to hold the process steps together without considering the real implementation in the subclass.Method overloading and method overriding are good examples of template method pattern. For example,
· Coercion polymorphism -- refers to a single operation serving several types through implicit type conversion.
· Overloading polymorphism -- refers to using a single identifier for different operations.
· Parametric polymorphism -- refers to a class declaration that allows the same field names and method signatures to associate with a different type in each instance of that class.
The add() in the following code example is a template method. It can take any numerical primitive types and the result can be casted to the type you want.Without using template method pattern, you may write more lines of code. The good thing is that you don't have any side effect by using specific designed method and you don't need to cast in or out.
The intent of the Observer pattern is to notify all dependent objects (or observers) automatically when the state in the subject changes. The JSF framework implements the Observer pattern in UI components. JSF technology has two kinds of built-in events: ActionEvent andValueChangedEvent. ActionEvent is useful in determining the activation of user interface components such as buttons. When a user clicks on the button, the JSF implementation notifies one or more action listeners added to the button. The button is activated or the state of the button (subject) changes. All listeners (or observers) are notified of the changes of state in subject that are added to the button. Similarly, when the value in the input UI component changes, the JSF implementation notifies ValueChangeListeners.
Example
The Observer defines a one-to-many relationship so that when one object changes state, the others are notified and updated automatically. Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and “observes” when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price which is broadcast to all of the bidders in the form of a new bid.
In conclusion
The JSF framework leverages Singleton, Model-View-Controller, Factory Method, State, Composite, Decorator, Strategy, Template Method, and Observer design patterns. It's a robust framework in that its architecture is based on already proven design patterns, which are utilized very nicely in the JSF framework.
What major patterns do the Java APIs utilize?
Design patterns are used and supported extensively throughout the Java APIs. Here are some examples:- The Model-View-Controller design pattern is used extensively throughout the Swing API.
- The getInstance() method in java.util.Calendar is an example of a simple form of the Factory Method design pattern.
- The classes java.lang.System and java.sql.DriverManager are examples of the Singleton pattern, although they are not implemented using the approach recommended in the GoF book but with static methods.
- The Prototype pattern is supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning.
- The Java Swing classes support the Command pattern by providing an Action interface and an AbstractAction class.
- The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern.
- The Adapter pattern is used extensively by the adapter classes in java.awt.event.
- The Proxy pattern is used extensively in the implementation of Java's Remote Method Invocation (RMI) and Interface Definition Language (IDL) features.
- The structure of Component and Container classes in java.awt provide a good example of the Composite pattern.
- The Bridge pattern can be found in the separation of the components in java.awt (e.g., Button and List), and their counterparts in java.awt.peer.
Which patterns were used by Sun in designing the Enterprise JavaBeans model?
- Factory Method: Define a interface for creating classes, let a subclass (or a helper class) decide which class to instantiate.
This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject implementations. They are actually created by a generated container class. See InitialContextFactory interface that returns an InitialContext based on a properties hashtable.
- Singleton: Ensure a class has only one instance, and provide a global point of access to it.
There are many such classes. One example is javax.naming.NamingManager
- Abstract Factory: Provide an interface for creating families of relegated or dependent objects without specifying their concrete classes.
We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has methods to get InitialContext.
- Builder: Separate the construction of a complex factory from its representation so that the same construction process can create different representations.
InitialContextFactoryBuilder can create a InitialContextFactory.
- Adapter: Convert the interface of a class into another interface clients expect.
In the EJB implementation model, we implement an EJB in a class that extends SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces. EJB container generates a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class and provides declarative transaction, persistence support.
- Proxy: Provide a surrogate for other object to control access to it.
We have remote RMI-CORBA proxies for the EJB's.
- Memento: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Certainly this pattern is used in activating/passivating the enterprise beans by the container/server.
Subscribe to:
Posts (Atom)
