先看一段很简单的代码
public class first {
public static void main(String[] args) {
company company = new company(new you());
company.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实角色,you结婚
class you implements Marry{
@Override
public void HappyMarry() {
System.out.println("i am marry");
}
}
//代理角色,帮你结婚
class company implements Marry{
//代理真实目标角色
private Marry marry;
public company(Marry marry) {
this.marry=marry;
}
@Override
public void HappyMarry() {
before();
this.marry.HappyMarry();
after();
}
private void before(){
System.out.println("结婚前");
}
private void after(){
System.out.println("结婚后");
}
}
代理模式总结
1.真实对象和代理对象要实现同一个接口
2.代理对象要代理真实角色
好处
代理对象可以做很多真实对象无法做的事情,真实对象可以专注做自己的事情