静态代理

代理主要具有什么作用?
可以隐藏目标类的具体实现;
可以在不修改目标代码的情况下能够对其功能进行加强。

代码实现

//定义接口
public interface SomeService {

	void printMessage();
	
	String toUp();
}



//定义接口实现类

import com.service.SomeService;

public class SomeServiceImpl implements SomeService{

	
	public SomeServiceImpl() {
		System.out.println("无参构造执行");
	}

	@Override
	public void printMessage() {
		// TODO Auto-generated method stub
		System.out.println("SomeServiceImpl.printMessage()方法执行");
	}

	@Override
	public String toUp() {
		// TODO Auto-generated method stub
		return "xuwei";
	}

}

//定义代理对象,实现相同的接口,并进行增强处理


import com.service.SomeService;

public class SomeServiceProxy implements SomeService{

	SomeService target;
	
	public SomeServiceProxy(SomeService target) {
		super();
		this.target = target;
	}
	
	public SomeServiceProxy() {
		super();
	}
	
	public String toUp(){
		return target.toUp().toUpperCase();
	}
	
	
	@Override
	public void printMessage() {
		// TODO Auto-generated method stub
		System.out.println("SomeServiceProxy.printMessage()");
	}
}


//测试


import com.proxy.SomeServiceProxy;
import com.service.SomeService;
import com.service.impl.SomeServiceImpl;

public class SomeProxyTest {

	public static void main(String[] args) {
		SomeService ss=new SomeServiceImpl();
		SomeService sp=new SomeServiceProxy(ss);
		String up = sp.toUp();
		System.out.println(up);
		sp.printMessage();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值