Design Pattern in EJB Applications

sponsored links
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 =?",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
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.

Aggregate
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.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Design Pattern in EJB Applications

  • Project manager qualities

    / ** Disclaimer: the text content from the network ** / Lot of people think that the project manager is always associated with "the ideal and the glorious" concomitant, in fact, as a interested in improving the flow of Chinese software deve ...

  • Demand assessment and demand for testing

    In the software development process, needs analysis is the beginning of the work, needs analysis, or if the details are not doing enough to deviate from the user requirements, then the project will bring about the extinction often disaster. So how to ...

  • Designed with the real coding

    Software development process at the design and coding, both organizations (as well as other details of the project controllability requirements) engineering method is XP ah, UPS ah what the design phase is to cover the entire software development pro ...

  • Hibernate's cache management

    Carried ] [http ://www.cnblogs.com/eflylab/archive/2007/01/11/617276.html Cache is the cache, it is often to improve system performance are the most important means to serve as a reservoir of data and the role of a buffer. Cache for the substantial r ...

  • The real design and coding

    Software development process at the design and coding, both organizations (as well as other details of the project controllability requirements) engineering method is XP ah, UPS ah what the design phase is to cover the entire software development pro ...

  • ActiveMQ practice the road (four) ActiveMQ 4.x + JBoss 4.x MDP actual articles

    Keyword: ActiveMQ ActiveMQ practice the road (four) ActiveMQ 4.x + JBoss 4.x MDP actual articles At <<ActiveMQ Practice ( Three ) ActiveMQ 4.x +JBoss 4.x Consolidating articles >> which we compare in detail the ActiveMQ with JBoss integration

  • Real design pattern

    I hate the thought of the time to teach some provide a lot of code, because I think the thought process of acceptance should be a pleasure to read as a novel process, rather than spend a lot of brain power for a certain process details And this world ...

  • Software development sunflower Baodian [reprint]

    Master the ability to reuse code very familiar with the new API's fast. This is because, he once used a lot of the API, have a lot of reusable code. He knows what is available and what is deficient. He has been using Qt, also used by gtk +, also used

  • J2EE Architect road

    J2EE Architect road Looking casual, working into the fifth year, the discovery came from the Java programmer to architect J2EE course. Found that computer to install a wide range of J2EE tools: JBuilder, WSAD, Eclipse, Rose, Together, Weblogic, Jtest, Opt

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries