package com.DesignPattern.Structural.Proxy;
public interface Subject {
// 定义一个请求方法
public void request();
}
package com.DesignPattern.Structural.Proxy;
public class ProxySubject implements Subject {
private Subject subject;
public ProxySubject(Subject subject) {
this.subject = subject;
}
// 实现请求方法
@Override
public void request() {
this.beforeRequest();
subject.request();
this.afterRequest();
}
//请求前的操作
private void beforeRequest() {
// 预处理
}
//请求后的操作
private void afterRequest() {
// 善后处理
}
}
package com.DesignPattern.Structural.Proxy;
public class RealSubject implements Subject {
@Override
public void request() {
// 业务处理逻辑
System.out.println("realSubject request");
}
}
package com.DesignPattern.Structural.Proxy;
public interface IGamePlayer {
public void killBoss();// 杀怪
public void upGrade();// 升级
}
package com.DesignPattern.Structural.Proxy;
public class GamePlayer implements IGamePlayer {
private String name = "";
public GamePlayer(String name) {
this.name = name;
}
@Override
public void killBoss() {
System.out.println(this.name + " killBoss");
}
@Override
public void upGrade() {
System.out.println(this.name + " upgrade level 1");
}
}
package com.DesignPattern.Structural.Proxy;
import java.util.Date;
public class GamePlayerProxy implements IGamePlayer {
private IGamePlayer player=null;
public GamePlayerProxy(IGamePlayer player){
this.player=player;
}
//记录打怪时间
private void log(){
System.out.println("打怪时间"+new Date().toString());
}
@Override
public void killBoss() {
this.log();
player.killBoss();
}
@Override
public void upGrade() {
player.upGrade();
this.count();
}
//计算升级所用的时间
private void count(){
System.out.println("upgrade cost time!");
}
}
package com.DesignPattern.Structural.Proxy;
public class ClientDemo {
public static void main(String[] args){
IGamePlayer player=new GamePlayer("Tom");
IGamePlayer proxy=new GamePlayerProxy(player);
proxy.killBoss();
proxy.upGrade();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载|Copyright ©2011-2015,Supernatural, All Rights Reserved.
DesignPattern_Java:Proxy Pattern
原文地址:http://blog.csdn.net/williamfan21c/article/details/48014565