标签:
package Proxy;
// 需要代理的行为接口定义 public interface GiveGift { public void giveDolls(); public void giveFlower(); public void giveChololate(); } package Proxy;
// 代理者拥有被代理者的实例即拥有被代理者的行为并且实现被代理者的需要代理的行为
public class Proxy implements GiveGift { private Pursuit p = null; public Proxy(SchoolGirl sg){ p = new Pursuit(sg); } public void giveChololate() { // TODO Auto-generated method stub p.giveChololate(); } public void giveDolls() { // TODO Auto-generated method stub p.giveDolls(); } public void giveFlower() { // TODO Auto-generated method stub p.giveFlower(); } } package Proxy;
// 代理者的行为实现 public class Pursuit implements GiveGift { private SchoolGirl sg = null; public Pursuit(SchoolGirl sg){ this.sg = sg; } public void giveChololate() { // TODO Auto-generated method stub System.out.println(sg.getName()+" 送你巧克力"); } public void giveDolls() { // TODO Auto-generated method stub System.out.println(sg.getName()+" 送你洋娃娃"); } public void giveFlower() { // TODO Auto-generated method stub System.out.println(sg.getName()+" 送你鲜花"); } } package Proxy;
// 实施行为的对象 public class SchoolGirl { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public SchoolGirl(String name){ this.name = name; } } package Proxy; public class testProxy { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SchoolGirl sg = new SchoolGirl("妹妹"); Proxy daili = new Proxy(sg); daili.giveChololate(); daili.giveDolls(); daili.giveFlower(); } }
代理者模式:
需要代理哪些行为?事例里指的是送花送巧克力等
行为不想暴露给谁?事例里指的是学生女孩
需要谁来为你做这些事?事例里指的是Proxy
谁需要代理,需要被隐藏?事例里指的是追求者
基本有需要被保护或者隐藏的对象都可以用代理,譬如秘书,助理都保护着董事长,小兵都冲在前面保护后方。
标签:
原文地址:http://www.cnblogs.com/wade-luffy/p/5670063.html