public interface IService {
void register(String name, String pswd, String email);
void login(String name,String pswd);
}
public class Service implements IService {
public void register(String name, String pswd, String email) {
// TODO Auto-generated method stub
System.out.println("存储用户信息到数据库");
}
public void login(String name, String pswd) {
if (name.equals("tang") && pswd.equals("123456"))
System.out.println("登陆成功");
else
System.out.println("登陆失败");
}
}
public class Logger {
public static void log(String str) {
File file = new File("log");
try{
FileOutputStream fos = new FileOutputStream(file,true);
BufferedOutputStream bos = new BufferedOutputStream(fos,256);
DataOutputStream dos=new DataOutputStream(bos);
dos.writeBytes(getCurrTime() + " INFO: " + str);
dos.writeBytes("/r/n");
dos.close();
}catch(Exception e){
e.printStackTrace();
}
}
private static String getCurrTime() {
Date date = new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(date);
}
}
public class MailSender {
public static void send(String email, String concept) {
System.out.println("向" + email + "发送邮件 内容为:" + concept + "的邮件");
}
}
public class ServiceProxy implements InvocationHandler {
Object obj;
public ServiceProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
Object result = null;
try {
if (m.getName().equals("register")) {
String name = (String) args[0];
Logger.log("register new user " + name);
result = m.invoke(obj, args);
String email = (String) args[2];
MailSender.send(email, "欢迎" + name + "注册为本系统的用户");
}
if (m.getName().equals("login")) {
String name = (String) args[0];
String pswd = (String) args[1];
Logger.log("user-"+name + " try to use password-"+pswd+" login.");
result = m.invoke(obj, args);
}
} catch (Exception e) {
}
// TODO Auto-generated method stub
return result;
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
IService service = genereteService();
service.register("tang", "123456", "tangyidong@gmail.com");
System.out.println("-----------------");
service.login("tang", "123456");
}
public static IService genereteService() {
return (IService) Proxy.newProxyInstance(IService.class
.getClassLoader(), new Class[] { IService.class },
new ServiceProxy(new Service()));
}
}
运行结果:
存储用户信息到数据库
向tangyidong@gmail.com发送邮件 内容为:欢迎tang注册为本系统的用户的邮件
-----------------
登陆成功
日志内容:
2008-06-29 20:39:27 INFO: register new user tang
2008-06-29 20:39:27 INFO: user-tang try to use password-123456 login.
参考:http://www.java3z.com/cwbwebhome/article/article2/21099.html?id=1883