Home >Java >Javagetting Started >What is proxy in java

What is proxy in java

(*-*)浩
(*-*)浩Original
2019-11-13 09:56:273765browse

The proxy in java is the Proxy Pattern, one of the 23 commonly used design patterns in java. Definition of proxy pattern: Provide a proxy for other objects to control access to this object.

What is proxy in java

The main function of the proxy mode is to provide a proxy for other objects to control access to this object. In some cases, one object does not want or cannot directly reference another object, and the proxy object can play an intermediary role between the client and the target object. (Recommended learning: java course)

The idea of ​​the proxy pattern is to insert a proxy object between the actual object and the caller in order to provide additional processing or different operations. These additional operations usually require communication with the actual object.

Interface class

public interface Italk {
    public void talk(String msg);
}

Implementation class

public class People implements Italk {
public String username;
public String age;
public String getName() {
return username;
}
public void setName(String name) {
this.username= name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public People(String name1, String age1) {
this.username= name1;
this.age = age1;
}
public void talk(String msg) {
System.out.println(msg+"!你好,我是"+username+",我年龄是"+age);
}
}

Agent class

public class TalkProxy implements Italk {
Italk talker;
public TalkProxy (Italk talker) {
//super();
this.talker=talker;
}
public void talk(String msg) {
talker.talk(msg);
}
public void talk(String msg,String singname) {
talker.talk(msg);
sing(singname);
}
private void sing(String singname){
System.out.println("唱歌:"+singname);
}
}

Application

public class MyProxyTest {
/**代理模式
* @param args
*/
public static void main(String[] args) {
//不需要执行额外方法的
Italk people1=new People("湖海散人","18");
people1.talk("No ProXY Test");
System.out.println("-----------------------------");
//需要执行额外方法的
TalkProxy talker=new TalkProxy(people1);
talker.talk("ProXY Test","七里香");
}
}

The above is the detailed content of What is proxy in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn