静态对象的实现

来源:互联网 发布:sql server2005企业版 编辑:程序博客网 时间:2024/06/04 20:08

静态对象实现
1、创建java project工程:07-proxy-static

2、src下创建一个业务接口ISomeService实现类:

package com.abc.service;
// 业务接口
public interface ISomeService {
// 业务方法
String doSome(int a, String b);
// 业务方法
void doOther();
}

3、来一个实现类SomeServiceImpl实现ISomeService接口
package com.abc.service;
// 目标类
public class SomeServiceImpl implements ISomeService {
// 目标方法
@Override
public String doSome(int a, String b) {
System.out.println(“执行业务方法doSome()”);
return a + b;
}
// 目标方法
@Override
public void doOther() {
System.out.println(“执行业务方法doOther()”);
}
}

4、客户测试类:Client
客户类不能直接访问SomeServiceImpl,只有权利访问doSome()方法,无权访问doOther();

package com.abc.test;

import com.abc.proxy.ServiceProxy;
import com.abc.service.ISomeService;

public class Client {
public static void main(String[] args) {
// 创建代理对象
ISomeService service = new ServiceProxy ();
// 调用代理对象的代理方法
String someResult = service.doSome(5, “月份”);
System.out.println(“someResult = ” + someResult);

    System.out.println("=========================");    // 调用代理对象的代理方法    service.doOther();}

}
5、创建代理类:ServiceProxy,并实现ISomeService接口

package com.abc.proxy;
import com.abc.service.ISomeService;
import com.abc.service.SomeServiceImpl;
import com.abc.utils.SystemUtils;

// 代理类
public class ServiceProxy implements ISomeService {
private ISomeService target;
//写到无参构造器中
public ServiceProxy() {
target = new SomeServiceImpl();
}

// 代理方法@Overridepublic String doSome(int a, String b) {    SystemUtils.doTx();    // 调用目标类的目标方法    String result = target.doSome(a, b);    SystemUtils.doLog();    return result;}// 代理方法@Overridepublic void doOther() {    SystemUtils.doTx();    // 调用目标类的目标方法    target.doOther();    SystemUtils.doLog();}

}
6、创建一个日志打印类:SystemUtils
package com.abc.utils;
// 系统级服务工具类
public class SystemUtils {

public static void doLog() {    System.out.println("记录日志");}   public static void doTx() {    System.out.println("开启事务");}

}

原创粉丝点击