Java中的代理模式实例

 

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

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

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:

 

posted @ 2017-12-18 16:05  ztt_tttt  阅读(644)  评论(0编辑  收藏  举报