在一个项目中,我看到了一些前雇员编写的代码。该人将其命名为适配器模式的实现,但我不确定。这是代码:
public class RowSetAdaptor implements java.io.Serializable {
private javax.sql.rowset.CachedRowSet cachedRowSet;
public RowSetAdaptor() throw SQLException {
cachedRowSet = new com.sun.rowset.CachedRowSetImpl();
}
public void populate(ResultSet resultSet) throw SQLException {
cachedRowSet.populate(resultSet);
}
public boolean next() throw SQLException {
cachedRowSet.next();
}
.... // different methods all using cachedRowSet
}
在我看来,类 RowSetAdaptor
正在限制对 CachedRowSet
接口(interface)的访问,因为并非 CachedRowSet
接口(interface)的所有方法都在 中可用>RowSetAdaptor
类。它真的是适配器模式吗?如果不是,那么这里使用的是哪种设计模式?
更新 [2015 年 2 月 24 日]
感谢@JB Nizet、@Fuhrmanator、@Günther Franke、@vikingsteve 和@Giovanni Botta 的回答。
如果我进行以下修改使其成为适配器模式会怎么样?
public interface RowSetI {
public boolean next() throws SQLException;
...
}
public class CachedRowSetAdapter implements RowSetI {
private javax.sql.rowset.CachedRowSet cachedRowSet;
public CachedRowSetAdapter() throw SQLException {
cachedRowSet = new com.sun.rowset.CachedRowSetImpl();
}
public void populate(ResultSet resultSet) throw SQLException {
cachedRowSet.populate(resultSet);
}
public boolean next() throw SQLException {
cachedRowSet.next();
}
...
}
public class JdbcRowSetAdapter implements RowSetI {
private javax.sql.rowset.JdbcRowSet jdbcRowSet;
public JdbcRowSetAdapter() throw SQLException {
jdbcRowSet = new com.sun.rowset.JdbcRowSetImpl();
}
public void populate(ResultSet resultSet) throw SQLException {
jdbcRowSet.populate(resultSet);
}
public boolean next() throw SQLException {
jdbcRowSet.next();
}
...
}
TIA
最佳答案
如果 RowSetAdaptor
类以任何方式适配 CachedRowSet
接口(interface),则 RowSetAdaptor
可以被视为 Adapter< 的实现/em> 设计模式(对象适配器)。
但在您的示例 list 中我看不到任何改编 - 操作只是转发到 cachedRowSet
对象 - 这样客户端就可以访问
CachedRowSet
直接接口(interface)。
RowSetAdaptor
引入了一个额外的间接级别,它
使设计复杂化并降低性能。
仅当客户端不能或不应直接访问 CachedRowSet
接口(interface)时才应使用它。
"A design pattern should only be applied when the flexibility it affords is actually needed."
[GoF book, page 31]
注意:
Adapter 设计模式(对象适配器)建议客户端引用一个接口(interface)(Target),使它们独立于具体的实现类(Adapter)。
在您的示例中,客户端引用(并依赖于)具体的 RowSetAdaptor
类。
有关进一步讨论,请参阅 GoF 设计模式内存/适配器设计模式,网址为 http://w3sdesign.com .
关于java - 它真的是适配器模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28283066/