首页 > 编程语言 > 详细

Java中的代理模式实例

时间:2017-12-18 16:52:37      阅读:211      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 优点:解耦和,降低了不同类之间的依赖性

孩子由于太小,不能自己吃奶需要保姆来喂,衣服脏了也不能自己洗,通过代理实现。

1 package object.agency;
2 
3 //吃饭代理
4 public interface EatAgency {
5     void canHelpEat();
6 }
1 package object.agency;
2 
3 //洗衣服代理
4 public interface ClothAgency {
5     
6     void canWashCloth();
7 }
 1 package object.agency;
 2 
 3 //baby找代理帮助他完成要做的事
 4 public class Baby {
 5     public EatAgency getEat() {
 6         return eat;
 7     }
 8     public void setEat(EatAgency eat) {
 9         this.eat = eat;
10     }
11     public ClothAgency getWash() {
12         return wash;
13     }
14     public void setWash(ClothAgency wash) {
15         this.wash = wash;
16     }
17     private EatAgency eat;
18     private ClothAgency wash;
19     
20     void eat(){
21         //需要找代理喂饭
22         eat.canHelpEat();
23     }
24     void wash(){
25         //需要找代理洗衣服
26         wash.canWashCloth();
27     }
28 }
 1 package object.agency;
 2 //Lucy可以帮孩子吃饭称为吃饭的代理
 3 public class Lucy implements EatAgency{
 4 
 5     @Override
 6     public void canHelpEat() {
 7         // TODO Auto-generated method stub
 8         System.out.println("lucy可以带孩子吃奶");
 9     }
10 
11 }
 1 package object.agency;
 2 //Mary可以帮孩子洗衣服成为洗衣服的代理
 3 public class Mary implements ClothAgency{
 4 
 5     @Override
 6     public void canWashCloth() {
 7         // TODO Auto-generated method stub
 8         System.out.println("Mary可以帮孩子洗衣服");
 9     }
10 
11 }
 1 package object.agency;
 2 
 3 //baby最终找到代理的测试
 4 public class BabyTest {
 5     public static void main(String[] args) {
 6         Baby baby=new Baby();
 7         Lucy lucy=new Lucy();
 8         Mary mary=new Mary();
 9         baby.setEat(lucy);
10         baby.setWash(mary);
11         baby.eat();
12         baby.wash();
13     }
14 }

  test:

技术分享图片

 

Java中的代理模式实例

原文:http://www.cnblogs.com/ztt0918/p/8058129.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!