关于Proxy和Decorator设计模式的疑问

个人认为Proxy模式和Decorator模式在编码实现上比较相似,主要还是看具体应用的场合。例如我们经常可以看到对java.sql.Connection重新包装的代码,不知道这属于哪种设计模式呢,还请大家指点。

public MyConnection implements Connection {
private Connection m_connection = null;

public MyConnection(Connection connection) {
m_connnection = connection;
}

//增加新的方法
public Timestamp getSystemTime() {
//......
}

//覆盖已经存在的方法
public void setAutoCommit(Boolean autoCommit) throws SQLException {
//......
}

//实现其它的方法
public Boolean getAutoCommit() throws SQLException {
return m_connection.getAutoCommit();
}

//......

}

这个例子应该是decorate模式。
一般proxy模式用在避免直接访问实际对象的环境下,比如远程访问,安全限制。
而decorate利用对实际对象的封装,来提供实际对象所没有的responsibility。

Adapter的变形--如果该为如下代码就是Adapter:


public MyConnection implements Connection,MyFunc {
private Connection m_connection = null;

public MyConnection(Connection connection) {
m_connnection = connection;
}

//增加新的方法,来自MyFunc
public Timestamp getSystemTime() {
//......
}

//覆盖已经存在的方法
public void setAutoCommit(Boolean autoCommit) throws SQLException {
//......
}

//实现其它的方法
public Boolean getAutoCommit() throws SQLException {
return m_connection.getAutoCommit();
}

//......

}

Proxy可以为对象提供细粒度的控制,例如Jive利用Proxy为对象提供方法级的安全控制。
Decorator使得客户端可以自由增强原对象的功能,例如你可以自由组合jive的filters,实现不同的过滤,还可以加入新的filter而完全不影响原有的filter,但是Jive对于Decorator的实现也是经过改变的(clone方法替代构造器),目的是为了提供缺省的Constructor,以便Class.forName