package com.test.design.proxy;
//代理接口,包含了被代理类所能处理的事情
public interface IProxy {
public void doWork();
public void doHappy();
}
package com.test.design.proxy;
//代理类 (同被代理类实现同一接口,这样就知道了被代理类到底都能干些什么)
public class Proxy implements IProxy {
private IProxy proxied;//被代理对象
public Proxy(){
this.proxied = new Proxied();
}
public Proxy(IProxy proxied){
this.proxied = proxied;
}
@Override
public void doHappy() {
this.proxied.doHappy();
}
@Override
public void doWork() {
this.proxied.doWork();
}
package com.test.design.proxy;
//被代理类
public class Proxied implements IProxy {
@Override
public void doHappy() {
System.out.println("我很开心..");
}
@Override
public void doWork() {
System.out.println("我在干活..");
}
}
package com.test.design.proxy;
public class Employer {
public static void main(String[] args) {
Proxy proxy = new Proxy(new Proxied());
proxy.doWork();
proxy.doHappy();
}
}
代理模式主要使用了java的多态,干活的是被代理类,代理类主要是接活的,你让我干活,我就交给幕后的类去干。