[TOC]
> 静态代理在使用时,需要定义**接口或者父类**,被代理对象与代理对象一起实现相同的接口或者是继承相同父类.
### 接口
IUserDao.java
~~~
package com.yc.model.Service;
public interface IUserDao {
void save();
}
~~~
### 目标对象:
UserDao.java
~~~
package com.yc.model.Service.Impl;
import com.yc.model.Service.IUserDao;
public class UserDao implements IUserDao {
@Override
public void save() {
System.out.println("保存数据");
}
}
~~~
### 代理对象:
UserDaoProxy.java
~~~
package com.yc.model.Proxy;
import com.yc.model.Service.IUserDao;
public class UserDaoProxy implements IUserDao {
//接收保存目标对象
private IUserDao target;
//代理的构造函数,被代理者传递进来
public UserDaoProxy(IUserDao target){
this.target=target;
}
@Override
public void save( ) {
System.out.println("开始事务");
target.save();
System.out.println("提交事务");
}
}
~~~
### 测试
~~~
package com.yc.model;
import com.yc.model.Service.IUserDao;
import com.yc.model.Service.Impl.UserDao;
public class Test {
public static void main (String[] args){
//目标对象
IUserDao target =new UserDao();
//代理对象
UserDaoProxy proxy = new UserDaoProxy(target);
//执行的是代理的方法
proxy.save();
}
}
~~~
### 执行结果
![](https://img.kancloud.cn/ce/a2/cea26439fc543962e1eeea66e31e3780_1040x556.png)