1、介绍。
先创建java代码,再进行编译。在运行前,代理类的.class文件已存在。事先知道要代理的是什么,通常只代理一个类。
优点:不需要知道委托类(实现类),只需知道代理即可。
缺点:(1)代码重复。代理类和委托类(实现类)实现了相同的接口。
(2)维护复杂。接口增加一个方法,代理类和委托类(实现类)都需要实现此方法。
(3)不灵活。代理类和委托类(实现类)的关系为一对一,无法一对多。
2、代码。Proxy.java、StaticProxyInherit.java、StaticProxy.java、UserServiceImpl.java、IUserService.java、User.java。
package com.zxj.test.proxy;
import com.zxj.dao.entity.User;
import com.zxj.dao.service.impl.UserServiceImpl;
public class Proxy {
private static void staticProxy() {
User user = new User();
user.setAge(11);
user.setName("卓小杰");
//继承委托类(实现类)的方式
StaticProxyInherit staticProxyInherit = new StaticProxyInherit();
staticProxyInherit.printInfo(user);
//实现接口的方式
StaticProxy staticProxy = new StaticProxy(new UserServiceImpl());
staticProxy.printInfo(user);
}
public static void main(String[] args) {
staticProxy();
}
}
package com.zxj.test.proxy;
import com.zxj.dao.entity.User;
import com.zxj.dao.service.impl.UserServiceImpl;
public class StaticProxyInherit extends UserServiceImpl {
@Override
public void printInfo(User user) {
System.out.println("before to do someThing");
super.printInfo(user);
System.out.println("after to do someThing");
}
}
package com.zxj.test.proxy;
import com.zxj.dao.entity.User;
import com.zxj.dao.service.IUserService;
import com.zxj.dao.service.impl.UserServiceImpl;
public class StaticProxy implements IUserService {
private UserServiceImpl userService;
public StaticProxy(UserServiceImpl userService) {
this.userService = userService;
}
@Override
public void printInfo(User user) {
System.out.println("before to do someThing");
userService.printInfo(user);
System.out.println("after to do someThing");
}
}
package com.zxj.dao.service.impl;
import com.zxj.dao.entity.User;
import com.zxj.dao.service.IUserService;
public class UserServiceImpl implements IUserService {
@Override
public void printInfo(User user) {
System.out.println(String.format("%s已经%d岁了", user.getName(), user.getAge()));
}
}
package com.zxj.dao.service;
import com.zxj.dao.entity.User;
public interface IUserService {
void printInfo(User user);
}
package com.zxj.dao.entity;
public class User {
private String name;
private int age;
public User(){
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3、结果。
|
|