式的Bridge模式,判断是否是某种模式,主要依据其参与者的种类和相互关系,我们先看看Bridge模式的定义和参与者:
Bridge模式是将抽象和行为划分开来,各自独立,但能动态的结合起来(好象搭建了一座桥)。在本例中,是将商业逻辑和数据库访问这样的行为划分开来,数据库访问专门放置在DAO中了。
Bridge模式需要两个接口(抽象类和接口通称为接口),一个用来封装抽象部分,本例中是封装商业逻辑,是CatalogEJB;还有一个是封装行为(Implementor),本例中是CatalogDAO,看看CatalogDAO代码:
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模式中参与者还需要有行为接口的具体实现(ConcreteImplementor),在本例中是CatalogDAOImpl,虽然在目前宠物店中只有一个ConcreteImplementor,但是可扩展为到Mysql XML等数据源访问,比如你可以自己新增一个叫CatalogDAOImplMysql,也是作为CatalogDAO的子类。
看看CatalogDAO的一个子类CatalogDAOImpl的代码:
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());
}
}
//具体Select语句在这里出现,这里主要是Oracle 数据库的访问语句
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),
|