代理模式
简单代理
//租房接口
public interface RentHourseInterface {
public void rent();
}
public class RentHouse implements RentHourseInterface {
private String name;
public RentHouse(String name) {
this.name = name;
}
@Override
public void rent() {
System.out.println(this.name+"租房");
}
}
//中介除了有代理租房还有收钱功能
public interface Proxy {
public void getMoney();
}
public class RentHouseProxy implements RentHourseInterface,Proxy{
private RentHourseInterface rentHourseInterface=null;
public RentHouseProxy(String name) {
this.rentHourseInterface = new RentHouse(name);
}
@Override
public void rent() {
rentHourseInterface.rent();
}
@Override
public void getMoney() {
System.out.println("中介收费");
}
}
//场景类
RentHouseProxy zhang = new RentHouseProxy("zhang");
zhang.rent();
//代理类实现多个接口,实现功能的增强
zhang.getMoney();
强制代理
/**
* 参与开会
*/
public interface SmallMeeting {
public void participate();
}
/**
* 董事长开会,但是没有时间,需要找到自己的秘书去替自己开会
*/
public class ChairMan implements SmallMeeting{
private SmallMeeting proxy=null;
private String name;
public ChairMan(String name) {
this.name = name;
}
public SmallMeeting getProxy(){
this.proxy=new SecretaryProxy(this);
return this.proxy;
}
@Override
public void participate() {
if(this.proxy!=null){
System.out.println("董事长"+this.name+"授权秘书替自己去参加会议");
}else{
System.out.println("没空");
}
}
}
/**
* 秘书代理参加会议
*/
public class SecretaryProxy implements SmallMeeting{
private SmallMeeting chairman;
public SecretaryProxy(SmallMeeting chairman) {
this.chairman = chairman;
}
@Override
public void participate() {
chairman.participate();
}
}
ChairMan chairMan = new ChairMan("zs");
//找到代理秘书
SmallMeeting proxy = chairMan.getProxy();
proxy.participate();
chairMan.participate();
ChairMan chairMan1 = new ChairMan("ls");
chairMan1.participate();
动态代理
public interface Buy {
public void buy();
}
public class BuyCloth implements Buy {
public void buy(){
System.out.println("买衣服");
}
}
public class MyInvocationHandler implements InvocationHandler {
private final Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("----------------------------");
return method.invoke(target,args);
}
}
public class Factory {
public static void main(String[] args) {
Buy o = (Buy) get(new BuyCloth());
o.buy();
}
public static Object get(Object target){
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new MyInvocationHandler(target));
}
}