概述
代理是一种模式,提供了对目标对象的间接访问方式,即通过代理访问目标对象。如此便于在目标实现的基础上增加额外的功能操作,前拦截,后拦截等,以满足自身的业务需求,同时代理模式便于扩展目标对象功能的特点也为多人所用。
静态代理的总结
优点:可以做到不对目标对象进行修改的前提下,对目标对象进行功能的扩展和拦截。
缺点:因为代理对象,需要实现与目标对象一样的接口,会导致代理类十分繁多,不易维护,同时一旦接口增加方法,则目标对象和代理类都需要维护。
通过一个案例演示静态代理。
Host 表示房主,他的主要功能是出租房屋
proxy 中介,代替房主出租房屋。用户直接与中介交互,中介内部在调用房主内的方法。
第一步:增加maven依赖
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.spring02</groupId>
<artifactId>spring02_static_proxy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
</dependencies>
</project>
第二步:编写Rent接口
Rent.java
package org.spring02;
/**
* 房屋出租接口
*/
public interface Rent {
public void rent();
}
第三步:编写Host类(房主),该类实现Rent接口。
Host.java
package org.spring02;
/**
* 房主类
*/
public class Host implements Rent {
/**
* 房主出租房屋
*/
public void rent() {
System.out.println("房主出租房屋!");
}
}
第四步:编写Proxy类(中介),该类实现Rent接口
proxy.java
package org.spring02;
/**
* 房屋中介类
*/
public class Proxy implements Rent {
//房主对象
Rent target;
public Rent getTarget() {
return target;
}
/**
* 将房屋对象注入进来。进行后续代理操作。
* @param target
*/
public void setTarget(Rent target) {
this.target = target;
}
/**
* 代理房主出租房屋
*/
public void rent() {
kanfang();
target.rent();//调用房主的租房方法。
shoufei();
}
public void kanfang(){
System.out.println("中介带人看房!");
}
public void shoufei(){
System.out.println("中介收费!");
}
}
第五步:编写测试类
Test.java
package org.spring02;
public class Test {
public static void main(String[] args) {
//构建房主对象(被代理对象)
Host host = new Host();
//构建中介对象(代理对象)
Proxy proxy = new Proxy();
//将房主对象放到中介对象中
proxy.setTarget(host);
//调用“中介”对象的租房方法,“中介”对象内部在调用“房主”对象的租房方法。
proxy.rent();
}
}
控制台结果
中介带人看房!
房主出租房屋!
中介收费!