一、概念:
代理模式只为对象提供一种通过代理的方式来访问并控制该对象行为的方法。在客户端不适合或者不能够直接引用一个对象时,可以通过该对象的代理对象来实现对该对象的访问,可以将该代理对象理解为客户端和目标对象之间的中介者。
二、创建Company接口:
package Proxy;
public interface Company {
void findWorker(String title);
}
三、创建HR实现类:
package Proxy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HR implements Company {
private final static Log logger = LogFactory.getLog(HR.class);
@Override
public void findWorker(String title) {
logger.info("I need find a worker, title is: " + title);
}
}
四、创建Proxy代理类:
package Proxy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.HashMap;
import java.util.Map;
public class Proxy implements Company {
private final static Log logger = LogFactory.getLog(Proxy.class);
private HR hr;
public Proxy(){
super();
this.hr = new HR();
}
@Override
public void findWorker(String title) {
hr.findWorker(title);
String worker = getWorker(title);
logger.info("find a worker by proxy, worker name is: " + worker);
}
private String getWorker(String title) {
Map<String, String> workerList= new HashMap<String, String>() {
{
put("Java", "张三");
put("Python", "李四");
put("Php", "王五");
}
};
return workerList.get(title);
}
public static void main(String[] args) {
Company company = new Proxy();
company.findWorker("Java");
}
}
五、代理设计模式优势:
代理模式的优势在于当你需要添加或修改新的业务功能 ,不需要修改原来的代码,而是通过添加新的类来代理之前的逻辑。