设计模式——代理模式
代理模式:
为其他对象提供一种代理以控制对这个对象的访问。
代理模式一般分为四种:
类图:其中
Subject类定义了公用接口
RealSubject和Proxy实现Subject,这样在任何使用RealSubject的地方都可以使用Proxy
实例:
吕秀才让燕小六代其向郭芙蓉求婚。
Ted让Marshall代其向Robin送鲜花、巧克力、洋娃娃。
类图:
代码
IGiveGift接口,相当于Subject
package cn.edu.tju.proxyPattern;//Subject接口public interface IGiveGift {public void giveDolls();public void giveFlowers();public void giveChocolate();}?
Persuit类,相当于RealSubject
package cn.edu.tju.proxyPattern;//RealSubject类public class Persuit implements IGiveGift{private SchoolGirl mm;public Persuit(SchoolGirl mm){this.mm = mm;}@Overridepublic void giveChocolate() {// TODO Auto-generated method stubSystem.out.println(mm.getName() + " 送你巧克力");}@Overridepublic void giveDolls() {// TODO Auto-generated method stubSystem.out.println(mm.getName() + " 送你洋娃娃");}@Overridepublic void giveFlowers() {// TODO Auto-generated method stubSystem.out.println(mm.getName() + " 送你鲜花");}}?
Proxy类
package cn.edu.tju.proxyPattern;//Proxy类public class Proxy implements IGiveGift{private Persuit persuit;public Proxy(SchoolGirl mm){//Proxy与Persuit是关联关系,体现在当实例化Proxy的同时实例化Persuitthis.persuit = new Persuit(mm);}@Overridepublic void giveChocolate() {// TODO Auto-generated method stubpersuit.giveChocolate();}@Overridepublic void giveDolls() {// TODO Auto-generated method stubpersuit.giveDolls();}@Overridepublic void giveFlowers() {// TODO Auto-generated method stubpersuit.giveFlowers();}}?
SchoolGir类,辅助
package cn.edu.tju.proxyPattern;//辅助类public class SchoolGirl {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}?
Test类
package cn.edu.tju.proxyPattern;//测试类public class Test {public static void main(String[] args){SchoolGirl mm = new SchoolGirl();mm.setName("Robin");Proxy proxy = new Proxy(mm);proxy.giveChocolate();proxy.giveDolls();proxy.giveFlowers();}}?