相当于将类和方法分离开
1.创建编写一个接口,提取收租金和签合同方法(拟成房东租客之间的收租金问题)
package cn.itsource._06_proxy_static;
/**
* 抽象主题角色
*/
public interface IRent {
/**
* 收租
*/
void rent();
/**
* 签合同
*/
void asign();
}
2.创建编写两个实现类
将实际的功能写在loadlord中
运行时将 loadlord对象传入Intermidary中进行调用方法
就是把方法和类分离开
package cn.itsource._06_proxy_static;
/**
* 房东:真实主题角色
*/
public class Landlord implements IRent{
public void rent() {
System.out.println("房东收租金");
}
public void asign() {
System.out.println("房东签合同");
}
}
package cn.itsource._06_proxy_static;
/**
* 中介:代理主题角色
*/
public class Intermidary implements IRent {
private IRent rent;
public Intermidary(IRent rent){
this.rent = rent;
}
public void rent() {
//调用之前插入业务逻辑
System.out.println("调用之前插入业务逻辑");
//调用真实主题角色的相同方法
this.rent.rent();
//调用之后插入业务逻辑
System.out.println("调用之后插入业务逻辑");
}
public void asign() {
//调用之前插入业务逻辑
System.out.println("调用之前插入业务逻辑");
//调用真实主题角色的相同方法
this.rent.asign();
//调用之后插入业务逻辑
System.out.println("调用之后插入业务逻辑");
}
}
3.创建编写一个测试类
传入对象可以调用方法
package cn.itsource._06_proxy_static;
import org.junit.Test;
public class StaticProxyTest {
@Test
public void test() throws Exception{
//创建一个被代理对象
IRent rent = new Landlord();
//创建一个代理对象
Intermidary proxy = new Intermidary(rent);
//调用代理对象的方法
proxy.asign();
proxy.rent();
}
}