First, the proxy pattern definition:
Provides a proxy for other objects to control access to this object.
Second, the model explanation
Proxy proxy mode is a structural design pattern, the main problem is: The problem of direct access to the object, such as: the object to be accessed on the remote machine. In object-oriented systems, there are some objects that for some reason (such as object creation overhead, or some operations require security control, or require out-of-process access), direct access can cause a lot of trouble for the user or system structure, and we can add a layer of access to this object when we access it. This access layer is also called an agent. Proxy mode is the most common pattern in our lives, for example, we do not have to buy train tickets to the railway station to buy, you can go to some of the train ticket sale point to buy. The letter is not necessarily sent by himself, can be entrusted to the post office, by the Post Office to send the letter to the destination, in real life there are many such examples, do not enumerate.
Third, the structure chart
The proxy mode structure is shown below:
四、一个 Example
To give a more vulgar example, a boy boy like a Girl girl, the boy always want to know the girl, go straight to greet with the girl, and feel embarrassed (the boy is more shy). So the boy came up with a way to entrust the girl's roommate proxy to help him fix this thing (get some information about girls, such as there is no BF, this is called the enemy, can win). The following is a program implementation for this example:
interface GirlInfo{
public void hasBoyFriend();
}
class Girl implements GirlInfo{
public void hasBoyFriend(){
System.out.println("还没有男朋友");
}
}
class Proxy implements GirlInfo{
private GirlInfo _girl;
public Proxy(GirlInfo girl){
_girl=girl;
}
public void hasBoyFriend(){
_girl.hasBoyFriend();
}
}
public class ProxyClient {
public static void main(String[] args) {
GirlInfo girl=new Girl();
Proxy proxy=new Proxy(girl);
proxy.hasBoyFriend();
}
}