Design Pattern in EJB Applications

What is a Design Pattern
Design patterns are a set of re-use, most people know, after cataloging, code design experience. For the use of design patterns are reusable code, so that the code more easily understood by others, and ensure the reliability code.

There is no doubt that design patterns have been on others in the system are win-win, and design patterns to enable the preparation of the real works of code, design patterns are the cornerstone of software engineering, as a building block, like masonry.

GOF's "Design Patterns" is the first design patterns to the theoretical height, and to standardization, this book has 23 kinds of basic design patterns, since, in the reusable object-oriented software development process, new many design patterns continue to emerge.

Design patterns and frameworks
Now, reusable object-oriented software system is now generally divided into three main categories: application toolkit and framework (Framework), we usually develop specific software applications; Java belong to the toolbox of the API; and constitute the framework are One particular type of software reusable design for a group of mutual cooperation category. EJB (Enterprise JavaBeans) are used in enterprise computing Java framework.

Framework for the definition of the application system is usually the overall structure of the relationship between classes and objects and so on design parameters in order to facilitate the implementation of specific applications can concentrate on specific details of the application itself. Record software application framework in the design of common decision-making, emphasize design reuse framework, so the framework of the design is bound to the use of design patterns.

In addition, design patterns help to frame the understanding of sophisticated framework for a variety of commonly used design patterns, if you are familiar with these design patterns, there is no doubt, you will quickly grasp the structure of the framework, we will generally contact the developer if a sudden EJB J2EE framework, etc., will feel particularly hard to learn, difficult to master, then switch to first master the design patterns is to analyze your EJB or J2EE system in a weapon.

EJB Design Pattern
The following design patterns from the perspective of the EJB framework and see what kind of? Prior to the assumption that perhaps you have already know the design pattern. Specialized design pattern, see my design on the model series.

EJB is to take multi-storey structure, the original database we are developing the basic application (business logic operations) Direct call database-driven, in the EJB, the commercial logic for computing and database separate from, the use of a number of structured models: Adapter mode and Bridge mode and so on. the benefits of doing so obviously there are three:

1. The separation of business logic layer and data access layer;
2. Can simultaneously support multiple databases;
3. However, the replacement of the database type, it will not design to the business logic code substantial modification.

EJB in the database call (such as select, such as issuing statements) referred to as session bean (Sessionbean), which will correspond to database records one by one entity bean called bean (Entity bean); by the two types of bean to complete the database visit.

Session bean and client applications in general are one correspondence, and client and database is closely linked entity bean, EJB entity bean (or directly in the session bean) and databases between the use of Adapter pattern and Bridge mode, the entity bean has no intention of and the addition of a layer between the database, called DAO (Data Access Object), DAO design pattern is actually a mixture.

Us to the pet shops in Java as an example of the Catalog, which is specialized in the treatment of the pet shops category in the database access, there are two main procedures: CatalogEJB and CatalogDAO, we look at the code from the specific design patterns are how applications.

Bridge mode and Adapter mode
We first look at the CatalogEJB code:

public class CatalogEJB implements SessionBean (
protected CatalogDAO dao;

/ / From the DAO Factory to obtain This is called a DAO Factory (factory) mode of an instance of
public void ejbCreate () (
try (
dao = CatalogDAOFactory.getDAO ();
catch (CatalogDAOSysException se) (
Debug.println ( "Exception getting dao" + se);
throw new EJBException (se.getMessage ());



We found that at CatalogEJB did not usually have conversations like bean operation on the database "select .. from." Operations such as SQL statements like these have been packaged into specific DAO implementation Medium (Concrete class).

Catalog at this example using the design mode Bridge mode, to determine whether certain models are mainly based on the types of its participants and mutual relations, we first take a look at the definition of Bridge mode and participants:

Bridge mode is to abstract and to conduct separate and independent, but can combine dynamic (like set up a bridge). In this case, is the commercial logic and database access of such an act to separate, specialized database access in place at the DAO.

Bridge mode requires two interface (abstract class and interfaces commonly known as the interface), a package used to abstract part of this case are packaged business logic, are CatalogEJB; there is a package are acts (Implementor), in this case Yes CatalogDAO, take a look at CatalogDAO code:

public interface CatalogDAO (

public Category getCategory (String categoryID, Locale l)
throws CatalogDAOSysException;

public Page getCategories (int start, int count, Locale l)
throws CatalogDAOSysException;

public Product getProduct (String productID, Locale l)
throws CatalogDAOSysException;

public Page getProducts (String categoryID, int start, int count, Locale l)
throws CatalogDAOSysException;

public Item getItem (String itemID, Locale l)
throws CatalogDAOSysException;

public Page getItems (String productID, int start, int size, Locale l)
throws CatalogDAOSysException;

public Page searchItems (String query, int start, int size, Locale l)
throws CatalogDAOSysException;


Bridge mode, players also have required the specific interface implementation acts (ConcreteImplementor), in this case are CatalogDAOImpl, although at present only one pet ConcreteImplementor, but can be extended to Mysql XML data sources, such as access, such as you can add a name CatalogDAOImplMysql, also as a sub-category CatalogDAO.

CatalogDAO take a look at a subset of category CatalogDAOImpl code:

public class CatalogDAOImpl implements CatalogDAO (
protected static DataSource getDataSource ()
throws CatalogDAOSysException (
try (
InitialContext ic = new InitialContext ();
return (DataSource) ic.lookup (JNDINames.CATALOG_DATASOURCE);
catch (NamingException ne) (
throw new CatalogDAOSysException ( "NamingException while looking"
+ "Up DB context:"
+ Ne.getMessage ());

/ / Specific Select statement here, here are the main Oracle database access statements

public Category getCategory (String categoryID, Locale l)
throws CatalogDAOSysException (

Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
Category ret = null;

try (
c = getDataSource (). getConnection ();

ps = c.prepareStatement ( "select a.catid, name, descn"
+ "From (category a join"
+ "Category_details b on"
+ "A.catid = b.catid)"
+ "Where locale =?"
+ "And a.catid =?",
ps.setString (1, l.toString ());
ps.setString (2, categoryID);
rs = ps.executeQuery ();
if (rs.first ()) (
ret = new Category (rs.getString (1). trim (),
rs.getString (2),
rs.getString (3));
rs.close ();
ps.close ();

c.close ();
return ret;
catch (SQLException se) (
throw new CatalogDAOSysException ( "SQLException:"
+ Se.getMessage ());



Bridge mode participants are summarized as follows:

Commercial logic of abstract class (CatalogEJB)

Abstract logic of commercial operation.
DAOImplementor call on.
Do not care about what are the specific data source to be used (either Oracle or JDBC or XML).
DAO (Data Access Object) (CatalogDAO)

Data source for the abstract operation behavior.
Provides a very convenient access and maintenance and administration of the API data structure.
DAOImplementor (CatalogDAOImpl may have CatalogDAOImplSybase CatalogDAOImplMysql, etc.)

Implementation specific content DAO interface.
Adapter to use mode-specific data source driver interface adapter to go DAO interface
Data source (Oracle, or Sybase database via JDBC API)

Provide access to specific database driver interface, such as including the connection pools.

In the use of the data source driver interface, the need to use the Adapter pattern, Adapter pattern is not related to the two categories together mustered use, Adapter pattern is to use the combination of the actual (composition) and inheritance (inheritance) in two ways renewable categories, at the famous "think in Java" the "Class Life" specifically referred to these two methods.

Obviously, if you Adapter mode Bridge mode and are familiar with, then the pet shops in the Catalog of understanding will be very fast, same, such as at pet shops in other parts of Order and other users can quickly understand the register.

Factory mode and Singleton patterns
The model similar to new, are used to create objects, use the Factory pattern in order to achieve the basic principles of object-oriented. Package (Encapsulation) and assigned (Delegation); will create the object with the use of object division. Therefore, in normal development process, to make full use Factory mode to create the object.

CatalogEJB in this case is to use Factory mode to obtain a specific instance of DAO objects, see the Notes CatalogEJB code. CatalogDAOFactory us take a look at the code:

public class CatalogDAOFactory (
public static CatalogDAO getDAO () throws CatalogDAOSysException (

CatalogDAO catDao = null;
try (
InitialContext ic = new InitialContext ();
String className = (String) ic.lookup (JNDINames.CATALOG_DAO_CLASS);
catDao = (CatalogDAO) Class.forName (className). newInstance ();
) Catch (NamingException ne) (

return catDao;

At CatalogDAOFactory can be based on system configuration file, dynamic access to DAO methods, the reason for the dynamic approach taken, of course, user-friendly to increase its own DAO methods, without having to modify code directly modify the configuration file as long as you can.

Here only if required to produce a CatalogDAOFactory example, can take Singleton pattern, Singleton to control the type of object instance creation, and allow the entire process at one point only to visit it. Singleton can only create a category in itself, are single-threaded.

public class CatalogDAOFactory (
private static CatalogDAO catDao = null;

public static CatalogDAO getIntance () (
if (catDao == null)
try (
InitialContext ic = new InitialContext ();
String className =
(String) ic.lookup (JNDINames.CATALOG_DAO_CLASS);
catDao = (CatalogDAO) Class.forName (className). newInstance ();
) Catch (NamingException ne) (

return catDao;


Well, at the call from CatalogEJB
dao = CatalogDAOFactory.getDAO ();
Proposal to change the
dao = CatalogDAOFactory.getIntance ();

Facade pattern
In EJB applications, there are two endpoints, the client is the client, the other end are EJB, usually between the two endpoints will increase the level to loose coupling between the two endpoints, such as at pet shops examples , taking into account the identity of different users have different operating processes, such as customers enter the register, the need to browse the directory, under the Order, and store managers to enter required to confirm or deny after the Order, or check inventory. These functions require Session bean and Entity bean completed.

However, if the client directly and these bean interaction, there will be the following questions:

1. The client must pay attention to and these beans all have links or interactive things, can not prevent the client may not be appropriate to use these beans.
2. If the API changes EJB, then the client must also modify some code. No doubt very poor scalability.
3. Even if these beans are on the same server, the client or by remote means to call them, for no reason causing network congestion.

Then we use the Facade pattern to solve this problem, Facade is defined as a set of subsystem interface to provide a consistent interface, it is clear that we need for the bean to provide a uniform external interface. The following diagram:

Medium at pet shops, ShoppingClientFacadeLocalEJB are all faced with the client to operate a unified interface, client operations and those not directly CustomerEJB such as EJB or ShoppingCartEJB have contact, but through ShoppingClientFacadeLocalEJB to contact. Code is as follows:

public class ShoppingClientFacadeLocalEJB implements SessionBean (

/ / And CustomerEJB Contact
public CustomerLocal getCustomer () throws FinderException (
if (userId == null) (
try (
InitialContext ic = new InitialContext ();
Object o = ic.lookup ( "java: comp / env / ejb / petstore / local / customer");
CustomerLocalHome home = (CustomerLocalHome) o;
customer = home.findByPrimaryKey (userId);
) Catch (javax.naming.NamingException nx) (

return customer;


/ / And ShoppingCartEJB Contact
public ShoppingCartLocal getShoppingCart () (
if (cart == null) (
try (
InitialContext ic = new InitialContext ();
Object o = ic.lookup ( "java: comp / env / ejb / cart / Cart");
ShoppingCartLocalHome home = (ShoppingCartLocalHome) o;
cart = home.create ();
) Catch (javax.ejb.CreateException cx) (
return cart;



Facade pattern Participants:

SessionFacade (ShoppingClientFacadeLocalEJB)

Provides a set of operational processes
The real job will be entrusted to the EJB-bean.
EJB-bean (CustomerEJB, ShoppingCartEJB and so on)

Business logic to perform basic operations
There is no call for SessionFacade.

This will not only greatly enhance the scalability, efficiency, and the client need only call a Remote for SessionFacade can, and SessionFacade will automatically locate the same server with its neighbors, those bean (CustomerEJB, ShoppingCartEJB and so on), no doubt reduce network congestion, improve the speed.

At the specific use of EJB, the use of appropriate design patterns, not only so that the code reusability can be increased to expand the most important thing is to improve the efficiency and speed, we know that EJB framework to consider large-scale system because of the affairs of all aspects of security, lack of efficiency of performance, then we at specific problems in a specific application, the use of design patterns can make up for this issue.

Proxy mode for example, can do for us during his visit must take enormous time to start the object, to provide an agent, this object will not be affected by the huge current speed, EJB those bean obviously belong to the great object (because they have repeated database operations, these are time〕.

Flyweight pattern is to avoid substantial content has the same categories of expenses (such as cost of memory), so that we can share a single category (element type). When you get a series of EJB from the string, which string has certainly much are repeated, then we can be to repeat the string stored in the flyweight pool (pool) in order to achieve shared.

分类:Java 时间:2009-03-04 人气:1237
blog comments powered by Disqus


  • Beyond design patterns 2010-10-23

    Depth beyond the outside of the design principles of design patterns Liu Xu Jin , software development engineer, IBM China Software Development Center Liu Xu Jin, IBM China Development Center software engineer, open source software, REST, Web Service

  • Quickly learn how to design patterns 2010-10-23

    Study design pattern for a long time, feeling has been hovering at the door. This is what design patterns, the most talked about, I think it was the interview, out to show a show, I understand this pattern, but also to understand which mode, you see

  • Introduction of design patterns grinding 2010-12-20

    First, long-term support to you my sincere thanks to friends! "Grinding Design Patterns" book has been listed specific information, please see the blog post, here is not to say more, lest they think JE has made a reasonable move. Introduction gr

  • Their understanding of the J2EE three-tier architecture (design patterns and software differences between the contact) 2009-06-18

    As Figure 3 layer 1.J2EE points: Server-side business logic (Business Logic Tier, and there is persistent data layers, Businness Tier and the EIS Tier), server-side presentation layer (Web Tier) and express the client layer (Client Tier) J2EE design

  • Their understanding of the J2EE three-tier architecture (design patterns and software differences between the links) 2009-06-21

    As Figure 3 layer 1.J2EE points: Server-side business logic (with Business Logic Tier and data layers of durable, Businness Tier and the EIS Tier), server-side presentation layer (Web Tier), and the client presentation layer (Client Tier) J2EE design

  • Design patterns and reusable object-oriented software 2010-07-23

    Seen before in the forum a good blog about design patterns. The most progress also strike while the iron is hot. Learning about design patterns reusable object-oriented software foundation. First give a brief summary of the definition of design patte

  • Experience in school projects, software design and design patterns 2010-03-29

    Although the specialty is software engineering, but the technologies are usually read by himself. In the study of software engineering, design patterns and other more abstract technologies, faced with obscure "textbook" is certainly at a loss wh

  • Application of design patterns in Java - Singleton 2010-04-23

    August 5, 2001 This article describes the Singleton design pattern in the basic concept, its function and use of a brief analysis, lists several methods typically achieve Singleton, and gives details of Java code. <! - START RESERVED FOR FUTURE USE I

  • Software project development process with the idea 2009-04-22

    INTRODUCTION Computer software, especially database software, has become the mainstream of contemporary computer applications. Thus software developers must have the right to develop the means to understand the main software development process, so t

  • Introduction and application of design patterns IOU 2009-05-17

    Principle IOU idea is that the debt in the handling of the relationship between the daily effective way, namely: * The debtor through reliable third-party escrow account to the creditor issuing IOU debt obligations; * The debtor through the escrow ac

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.032 (s). 13 q(s)