我会给你一个例子,我想它会帮助你了解代理的目的/能力,并尝试展示控制对对象的访问的含义。
假设我有一个DataStore
实现给定接口的对象(或实体)存储IModel
。
我的合同如下:
public interface IDataStore(){
// Return a given model by its id
public IModel getModelById(Long ID);
// Return the set of models that were modified by DataStore Clients.
public Collection<IModel> getModifiedModels();
}
第二种方法合同有点复杂,解决起来很麻烦。一个(复杂的)解决方案是保留每个IModel
返回的副本,然后在原始元素之间进行比较。使用代理模式,我们的 DataStore 可以以优雅的方式履行他的合同:当查询具有给定 id 的模型时,他实际上会向您返回一个代理,该代理会将任何修改通知回数据存储。
出于说明目的,以下是合同解决方案的外观:
// The following is equivalent to "Subject" using your nomenclature
public interface IModel{
public Long getId()
public void setId(Long id);
}
// The following is equivalent to the "RealSubject"
public class RealModel implements IModel{
Long id;
public void getId(){
return id;
}
public void setId(Long newid){
this.id = newid;
}
}
最后是我们的代理:
public class ModelProxy extends RealModel implements IModel{
IModel proxiedModel;
DataStore datastore;//our datastore
public ModelProxy(IModel model, DataStore ds){
proxiedModel=model;
datastore = ds;
}
public void setId(Long newid){
datastore.addModified(this);
// (Assume the DataStore implementation has the addModified method)
// The more important here is that we are really "controlling access" to
// our model : before allowing client to modify the id, we're
// notifying the store of the modification, and the client hasn't to know about
// that as he's only aware of the IModel interface contract.
this.id = newid;
}
}