I'll give you an example that i suppose will help you get the purpose/power of a proxy and try to show the meaning of controlling access to an object.
Assume I have a store DataStore
of objects (or entities) implementing a given interface IModel
.
My contracts are as follows:
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();
}
The second method contract is is a bit sophisticated and can be cumbersome to solve. A (sophisticated) solution would be to keep a copy of each IModel
returned, then make a comparison between the original elements.
Using the proxy pattern, our DataStore can fulfill his contract in an elegant way : when queried about a model with a given id, he'll actually returns to you a proxy that notifies back the data store of any modification.
For illustration purpose, here is how should look like the solustion to the contract:
// 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;
}
}
and finally here is our proxy :
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;
}
}