欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

静态代理

程序员文章站 2023-12-29 23:42:04
...
package javaDesignModule.staticproxy;

//抽象较色:申明真是对象与代理对象的共同接口
public interface TicketManager {
/**
* 售票
*/
public void soldTicket();

/**
* 改签
*/
public void changeTicket();

/**
* 退票
*/
public void returnTicket();
}

package javaDesignModule.staticproxy;

//真实主题角色
public class TicketManagerImpl implements TicketManager {

@Override
public void soldTicket() {
// TODO Auto-generated method stub
System.out.println("售票");
}

@Override
public void changeTicket() {
// TODO Auto-generated method stub
System.out.println("改签");
}

@Override
public void returnTicket() {
// TODO Auto-generated method stub
System.out.println("退票");
}

/**
* 身份验证
*/
public void checkIdentity(){
System.out.println("身份验证");
}
}

package javaDesignModule.staticproxy;

public class StaticProxyTicketManager implements TicketManager {

TicketManager ticketManager;

public StaticProxyTicketManager(TicketManager ticketManager) {
this.ticketManager = ticketManager;
}

@Override
public void soldTicket() {
// TODO Auto-generated method stub
checkIdentity();
ticketManager.soldTicket();
}

@Override
public void changeTicket() {
// TODO Auto-generated method stub
checkIdentity();
ticketManager.changeTicket();
}

@Override
public void returnTicket() {
// TODO Auto-generated method stub
checkIdentity();
ticketManager.returnTicket();
}

public void checkIdentity(){
System.out.println("身份验证");
}

}

package javaDesignModule.staticproxy;

public class LogProxy implements TicketManager{

private TicketManager ticketManager;

LogProxy(TicketManager tm){
this.ticketManager = tm;
}

@Override
public void soldTicket() {
// TODO Auto-generated method stub
ticketManager.soldTicket();
log();
}

@Override
public void changeTicket() {
// TODO Auto-generated method stub
ticketManager.changeTicket();
log();
}

@Override
public void returnTicket() {
// TODO Auto-generated method stub
ticketManager.returnTicket();
log();
}

private void log(){
System.out.println("日志");
}
}

package javaDesignModule.staticproxy;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
TicketManager tm = new LogProxy(new StaticProxyTicketManager(new TicketManagerImpl()));
tm.soldTicket();
System.out.println("---------");
tm.changeTicket();

System.out.println("---------");

tm.returnTicket();
}

}
静态代理类:在程序运行前,代理类class文件就已经被编译了
优点:
1.对真实对象进行封装,不会修改目标类的代码
缺点:
1.多个不同类型目标对象需要代理时,就需要建立多个代理类,造成类数量增长
2.代理的冗余
3.编译期加入,不够灵活
相关标签: java 设计模式

上一篇:

下一篇: