Application of Design Pattern in EJB

Source: Internet
Author: User
Tags sybase database

What is the design model?
The design pattern is a set of items that are repeatedly used and known by most people and classified,CodeSummary of design experience. The design pattern is used to make code reusable, make it easier for others to understand, and ensure code reliability.

There is no doubt that the design model is a win-win solution for others and the system. The design model enables code compilation to be truly engineered. The design model is the foundation of software engineering, just like the building blocks.

Gof's "Design Pattern" is the first time that it has elevated the design pattern to a theoretical level and standardized it. This book has proposed 23 basic design patterns. Since then, during the development of reusable object-oriented software, a large number of new design patterns are emerging.

Design Pattern and framework
Now
Currently, reusable object-oriented software systems are generally divided into three categories: ApplicationsProgram
Toolbox and framework, the specific software we usually develop is an application; Java APIs belong to the Toolbox; and the Framework is a group of reusable designs that constitute a specific type of software.
Collaboration class. EJB (Enterprise JavaBeans) is a Java framework applied to enterprise computing.

The framework usually defines design parameters such as the relationship between the overall structure class and object of the application system, so that specific application implementers can focus on specific details of the application. The framework mainly records the common design decisions in software applications, and emphasizes design reuse. Therefore, the design model must be used in the framework design.

Another
In addition, the design pattern helps to understand the framework structure. Mature frameworks usually use multiple design patterns. If you are familiar with these design patterns, you will have no doubt that you will quickly master the structure of the Framework, general developers, such
If you suddenly access the EJB J2EE and other frameworks, you will find it particularly difficult to learn and master. Instead, you will first master the design mode, which is undoubtedly a powerful tool for you to analyze the EJB or J2EE system.

Design Pattern in EJB
Let's look at the EJB framework from the perspective of design patterns? Before that, assume that you have understood the design pattern. For specific design patterns, see my design patterns series.

EJB adopts a multi-layer structure. In the past, our database development was basically an application (business logic operation) that directly calls the database driver. in EJB, in order to completely separate the business logic computing from the database, multiple structured modes are used: adapter mode and bridge mode. there are three advantages:

1. the business logic layer and data access layer are separated;
2. Support multiple databases at the same time;
3. However, when the database type is changed, a large number of modifications to the commercial logic code will not be designed.

In EJB, Database Calling (such as issuing select statements) is called Session Bean (sessionbean), and the beans recorded in the corresponding database are called Entity Bean (Entity Bean ); these two types of beans are used to access the database.

Yes
Bean is generally one-to-one correspondence with client applications, while entity beans are closely related to the database. EJB is used between entity beans (or session beans directly) and databases.
The adapter mode and the bridge mode have no intention of having another layer between the Entity Bean and the database. They are called Dao (Data Access Object
), Dao is actually a mixture of design patterns.

Let's take catalog in a Java pet store as an example. This is a specialized pet category in a pet shop. There are two main programs for accessing the database: catalogejb and catalogdao, let's look at the specific code to see how the design pattern is applied.

Bridge and adapter Modes
Let's first look at the catalogejb code:

Public class catalogejb implements sessionbean {
Protected catalogdao Dao;

// Obtain a Dao from the DaO factory. This is an instance that calls the factory mode.
Public void ejbcreate (){
Try {
Dao = catalogdaofactory. getdao ();
}
Catch (catalogdaosysexception SE ){
Debug. println ("exception getting Dao" + Se );
Throw new ejbexception (SE. getmessage ());
}
}

....

}

We found that catalogejb does not have the "select .. from. "and other SQL operation statements, these are encapsulated into the specific implementation of Dao (concrete class ).

In the catalog example, the Bridge Mode of the design mode is used to determine whether it is a certain mode based on the types and relationships of its participants. Let's first look at the definition and participants of the Bridge Mode:

The Bridge Mode separates abstraction and behavior and is independent of each other, but can be dynamically combined (as if a bridge is built ). In this example, the behavior of business logic and database access is divided, and database access is specially placed in Dao.

The bridge mode requires two interfaces (abstract classes and interfaces are called interfaces). One is used to encapsulate the abstract part. In this example, the commercial logic is encapsulated and catalogejb is used. The other is the encapsulation behavior (implementor ), in this example, catalogdao is used to check the 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
In this mode, the participant also needs to have a specific implementation of the behavior interface (concreteimplementor). In this example, It is catalogdaoimpl, although currently only
A concreteimplementor, but can be extended to MySQL
For example, you can add catalogdaoimplmysql as a subclass of catalogdao.

Let's look at the code of catalogdaoimpl, a subclass of catalogdao:

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 ());
}
}

// The specific SELECT statement appears here, which is mainly the access statement of the Oracle database.

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.exe cutequery ();
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 ());
}

....

}

The Bridge Mode participants are summarized as follows:

Abstract business logic class (catalogejb)

Abstract business logic operations.
Call daoimplementor.
No matter what data source is used (whether it is Oracle, JDBC or XML ).
Dao (Data Access Object) (catalogdao)

Abstract operations on the data source.
It provides an API structure that facilitates access and maintenance of data management.
Daoimplementor (catalogdaoimpl may have catalogdaoimplsybase catalogdaoimplmysql, etc)

Implement specific Dao interface content.
Use the adapter mode to adapt a specific data source driver interface to the DaO interface.
Data Source (Oracle, or sybase database via jdbc api)

Provides driver interfaces for accessing a specific database, such as connection pools.

In
When using the data source driver interface, you need to use the adapter mode. The adapter mode is used to combine two irrelevant classes. The adapter mode is actually a combination.
(Composition) and inheritance (inheritance) two ways of regeneration class, specifically mentioned in the famous "think in Java" class regeneration.

Obviously, if you are familiar with the bridge and adapter modes, you can quickly understand the catalog in pet shops. Similarly, you can quickly understand other parts of pet shops, such as order user registration.

Factory mode and Singleton Mode
This mode is similar to new and used to create objects. The factory mode is used to implement the Basic Principles of object-oriented. encapsulation and Delegation. Therefore, during normal development, try to use the factory mode to create objects.

In this example, catalogejb obtains a specific Dao instance object in the factory mode. For more information, see the comments in the catalogejb code above. Let's take a look at the catalogdaofactory 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;
}

In catalogdaofactory, You can dynamically obtain the DAO method based on the system configuration file. The dynamic method is adopted, so that you can add your own DAO method without having to modify the code, you only need to modify the configuration file directly.

If you only need catalogdaofactory to generate an instance, you can adopt the singleton mode. Singleton aims to control the creation of class instance objects and allow the whole program to access it only at one point. Singleton can only create one class, which is a single thread.

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;

}
}

So the call from catalogejb
Dao = catalogdaofactory. getdao ();
To change
Dao = catalogdaofactory. getintance ();

Facade Mode
In
In an EJB application, there are two endpoints, one of which is the user end and the other is the EJB. A layer is usually added between the two endpoints to loosen the coupling between the two endpoints, for example, in the pet store example
Users of different identities have different operation procedures. For example, after a customer registers, they need to browse the Directory and place orders. When a store manager enters, they need to confirm or deny the order, or check the inventory. These functions need to be used
Session Bean and Entity Bean are completed.

However, if the user Directly Interacts with these beans, the following problems may occur:

1. the user end must pay attention to all related or interactive matters with these beans, and cannot prevent the user end from using these beans improperly.
2. If the ejb api changes, some code on the user end must also be modified. Undoubtedly, the scalability is poor.
3. Even if these beans are on the same server, the user end still calls them in remote mode, causing network congestion for no reason.

We use the facade mode to solve this problem. The definition of facade is to provide a consistent interface for a group of interfaces in the subsystem. Obviously, we need to provide a unified external interface for these beans. For example:

In
In pet shops, shoppingclientfacadelocalejb is a unified interface for all user-side operations. User-side operations are not directly related to those ejbs such
Customerejb or shoppingcartejb are associated, but they are all associated through shoppingclientfacadelocalejb. Code such
Below:

Public class shoppingclientfacadelocalejb implements sessionbean {
...

// Contact customerejb
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;
}

.....

// Contact shoppingcartejb
Public shoppingcartlocal getshoppingcart (){
If (Cart = NULL ){
Try {
Initialcontext Ic = new initialcontext ();
Object o = IC. Lookup ("Java: COMP/ENV/EJB/cart ");
Shoppingcartlocalhome home = (shoppingcartlocalhome) O;
Cart = home. Create ();
} Catch (javax. EJB. createexception CX ){
...
}
}
Return cart;
}

....

}

Facade mode participants:

Sessionfacade (shoppingclientfacadelocalejb)

Provides a set of Operation Procedures
Delegate the real work to the bean of the EJB.
EJB Bean (customerejb, shoppingcartejb, etc)

Perform basic business logic operations
No call to sessionfacade.

This
This not only greatly enhances the scalability, but also improves the efficiency. The user only needs to call sessionfacade once by using remote, and sessionfacade will automatically set
The neighboring beans (customerejb, shoppingcartejb, etc.) on the same server undoubtedly reduces network congestion and increases the speed.

Summary
In the specific use of EJB, the use of appropriate design patterns not only makes the code reusable and extensible, but also improves the efficiency and speed, we know that the EJB framework lacks efficiency and performance due to various issues such as transaction security in large systems. Therefore, we can use the design pattern to make up for this problem when dealing with specific applications.

For example, the proxy mode can provide a proxy for us to access a large object that takes a certain amount of time to expand. This will not affect the current running speed because of this huge object, the beans in EJB are obviously huge objects (because they have repeated database operations, these are very time-consuming 〕.

The flyweight mode avoids the overhead of a large number of small classes with the same content (such as memory consumption), so that everyone can share a class (Meta class ). when you want to obtain a series of strings from ejbs, and many of these strings must be repeated, we can store these repeated strings in the flyweight pool for sharing.

 

reference address: http://www.matrix.org.cn/thread.shtml? Topicid = 32626 & forumid = 15

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.