设计模式之代理模式

代理模式,今天复习了下,做了2个测试,一个是静态代理,一个是动态代理。

抄袭的理论知识,给自己涨点专业知识:
按照代理类的创建时期,代理类可分为两种。
1、静态代理类:由程序员创建或由特定工具自动生成源代码,再对其编译。在程序运行前,代理类的.class文件就已经存在了。
2、动态代理类:在程序运行时,运用反射机制动态创建而成。

模拟的是买电脑的一个demo

静态代理:

package com.design.test.mode.proxy;

/**
* 客户买电脑接口
* 在联想电脑代理商那里购买得到
* 静态代理模式,代理类和委托类实现同一个接口
* @author Share
*
*/
public class BuyPc {

public static void main(String[] args) {

new LenovoServiceProxy(new LenovoService()).sell();
}
}

/**
* 卖电脑服务接口
* @author Share
*
*/
interface ISellPcService{
void sell();
}

/**
* 联想厂家专卖店
* @author Share
*
*/
class LenovoService implements ISellPcService{

@Override
public void sell() {
// TODO Auto-generated method stub
System.out.println("出售一台联想笔记本");
}

}

/**
* 联想专卖店代理商
* @author Share
*
*/
class LenovoServiceProxy implements ISellPcService{

private LenovoService lenovoService;

public LenovoServiceProxy(LenovoService lenovoService){
this.lenovoService = lenovoService;
}

@Override
public void sell() {
// TODO Auto-generated method stub
this.doBefore();
lenovoService.sell();
this.doAfter();
}

public void doBefore(){
System.out.println("进购一台联想笔记本");
}

public void doAfter(){
System.out.println("登记出售的那台联想笔记本");
}
}





动态代理:

package com.design.test.mode.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class BuyPc2 {

public static void main(String[] args)throws Exception{
// TODO Auto-generated method stub
ServiceFactory.getServiceProxy(new LenovoService()).sell();
}

}

/**
* 服务工厂
* @author Share
*
*/
class ServiceFactory {

/**
* 生产接口实例
* @param service
* @return
* @throws Exception
*/
public static ISellPcService getServiceProxy(final ISellPcService service) throws Exception {
MyInvocationHandler handler = new MyInvocationHandler(service);
//方式一
// //创建动态代理类
// Class proxyClass = Proxy.getProxyClass(ISellPcService.class.getClassLoader(), new Class[]{ISellPcService.class});
// //创建动态代理类的实例
// return (ISellPcService)proxyClass.getConstructor(new Class[]{InvocationHandler.class})
// .newInstance(new Object[]{handler});
//方式二、最简单方式
return (ISellPcService)Proxy.newProxyInstance(ISellPcService.class.getClassLoader(), new Class[]{ISellPcService.class}, handler);
}

}

class MyInvocationHandler implements InvocationHandler{

private ISellPcService sellService;

public MyInvocationHandler(ISellPcService sellService){
this.sellService = sellService;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
this.doBefore();
Object result = method.invoke(sellService, args);
this.doAfter();
return result;
}

public void doBefore(){
System.out.println("进购一台联想笔记本");
}

public void doAfter(){
System.out.println("登记出售的那台联想笔记本");
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值