java静态代理

WorkIF.java

 

package com.wzh.test;

public interface WorkIf {

void doWork(String name);
}

 

work.java

 

package com.wzh.test;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Work implements WorkIf{


/**
* 在一段程序中,分为两种代码:
* 1.业务逻辑代码,即和业务相关的代码
* 2.和业务逻辑无关的代码,但是需要存在
* */
public void doWork(String name){
System.out.println(name+"努力工作...");//业务逻辑代码
}
public static void main(String[] args) {
// Work w=new Work();
// w.doWork("小明");

Work w=new Work();
WorkProxy wp=new WorkProxy(w);
wp.proxy("冠希");
}
}

 

myWork.java

package com.wzh.test;

public class myWork implements WorkIf{

@Override
public void doWork(String name) {
// TODO Auto-generated method stub
System.out.println(name+"偷懒的工作...");//业务逻辑代码
}

public static void main(String[] args) {
myWork w=new myWork();
WorkProxy wp=new WorkProxy(w);
wp.proxy("杰伦");
}
}

 

WorkProxy.java

 

package com.wzh.test;

import java.util.logging.Level;
import java.util.logging.Logger;

/*
* 代理类,帮助Work类写日志
* 1.代理类如何和被代理类管理起来
* */
public class WorkProxy {

private Logger logger=Logger.getLogger(this.getClass().getName());

private WorkIf work;

public WorkProxy(WorkIf work) {
super();
this.work = work;
}

public WorkProxy() {
super();
// TODO Auto-generated constructor stub
}

//代理方法
public void proxy(String name){
try {
logger.log(Level.INFO,name+"开始工作..."); //日志
//业务逻辑
work.doWork(name);//被代理类执行业务逻辑方法
logger.log(Level.INFO,name+"结束工作...");//日志
} catch (Exception e) {
logger.log(Level.SEVERE,name+"工作出现问题...");//日志
}
}
}

posted on 2013-10-11 20:44  上校  阅读(436)  评论(0编辑  收藏  举报