标签:interface private package public 送礼物
代理模式:代理者和被代理者实现共同的行为,然后让代理制调用被代理者完成这些行为。
示例说明:代理者Proxy 代理MrLi 给MrssHong 送礼物。
类图如下:
代码实现:
定义一个送礼物的接口:GiveGift
package com.zpj.designMode.proxy;//定义一个送礼物的接口public interface GiveGift { public void giveFlowers(); public void giveDolls(); public void giveChocolate(); }
实现MrLi:
package com.zpj.designMode.proxy;/** * MrLi会追女孩送礼物所以要实现接口GiveGift */public class MrLi implements GiveGift { private MrssHong hong;// 被追求着 public MrLi(MrssHong hong) { this.hong = hong; } @Override public void giveFlowers() { System.out.println("---------送花-------------" + hong.getName()); } @Override public void giveDolls() { System.out.println("---------送洋娃娃-------------" + hong.getName()); } @Override public void giveChocolate() { System.out.println("---------送巧克力-------------" + hong.getName()); } }
实现代理Proxy :
package com.zpj.designMode.proxy;public class Proxy implements GiveGift { private MrLi person;// 被代理人 public Proxy(MrssHong hong) { person = new MrLi(hong); } @Override public void giveFlowers() { person.giveFlowers(); } @Override public void giveDolls() { person.giveDolls(); } @Override public void giveChocolate() { person.giveChocolate(); } }
被送礼物者:MrssHong
package com.zpj.designMode.proxy;public class MrssHong { private String name; public MrssHong(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
测试类:
package com.zpj.designMode.proxy;import org.junit.Test;public class TestUnit { @Test public void test01() { MrssHong hong = new MrssHong("红小姐"); // 告诉代理者向谁送礼物,这个代理专属于MrLi Proxy proxy = new Proxy(hong); // 代理者送礼物 proxy.giveFlowers(); proxy.giveChocolate(); proxy.giveDolls(); } }
标签:interface private package public 送礼物
原文地址:http://zhanglida66.blog.51cto.com/12834458/1920492