一只小鸟初学设计模式(二)代理模式

       今天时间充裕,故有时间再学习另外一种设计模式,此种设计模式使用的比较多,尤其在经典的SSH框架中,故小生斗胆来分享一下自己的学习理解过程,望大神多多指教。

     话不多说,代码奉上,欢迎批评指正。

     

package cd.david.proxy;


/*
 * 这是代理和被代理的类都要实现的接口,表明他们有共同点,有共同点才能被代理
 * */
public interface IProxyPattern {
 /*
  *作为代理模式首先能被代理说明代理者与被代理者之间有一定共同之处
  *这样二者的代理才能实现,换句话说就是二者实现同一个接口
  */
     public void eat();
     public void tea();
}

 

*********************************************************************************************************

 

package cd.david.proxy;
/*
 *
 * 这是一个代理类,负责代理实现了同一个接口的奇他类
 *
 * **/
public class GirlsMother implements IProxyPattern {
 
 
 private IProxyPattern proxy;
 

 public GirlsMother(IProxyPattern proxy) {
  this.proxy = proxy;
 }

 @Override
 public void eat() {
  proxy.eat();
 }

 @Override
 public void tea() {
  proxy.tea();
 }

}

**********************************************************************

package cd.david.proxy;

/*
 *
 * 这是一个被代理的类
 * **/
public class Girl implements IProxyPattern {

 @Override
 public void eat() {
  System.out.println("Hello,i am the girl  you want to have dinner together!");
 }

 @Override
 public void tea() {
  System.out.println("Hello,i am the girl  you want to drink tea together!");

 }

}

*******************************************************************************

package cd.david.proxy;

/*
 * 这是另一个你想要被代理的类
 *
 *
 * **/
public class AotherGirl implements IProxyPattern {

 @Override
 public void eat() {
  System.out.println("Hello,i am the aothergirl  you want to have dinner together!");
 }

 @Override
 public void tea() {
  System.out.println("Hello,i am the aothergirl  you want to have dinner together!");
 }

}

************************************************************************************

接下来是测试类:

package cd.david.test.strategy;

import cd.david.proxy.AotherGirl;
import cd.david.proxy.Girl;
import cd.david.proxy.GirlsMother;

public class ProxyTest {

 public static void main(String[] args) {
  /*
   * 你表面上是在和女孩的母亲一起吃饭喝茶,实际还是你和女孩在吃饭喝茶
   * */
         GirlsMother girlMother = new GirlsMother(new Girl());
         girlMother.eat();
         girlMother.tea();
        
         /*
          *
          * 如果某一天你改变心意了,喜欢她的二女儿,你可以让该母亲代理她的二女儿,这样你实际交往的对像又变成了她的二女儿
          * **/
         GirlsMother aotherGirlMother = new GirlsMother(new AotherGirl());
         aotherGirlMother.eat();
         aotherGirlMother.tea();
 }
}

*****************************************************************

测试结果奉上:

Hello,i am the girl  you want to have dinner together!
Hello,i am the girl  you want to drink tea together!
Hello,i am the aothergirl  you want to have dinner together!
Hello,i am the aothergirl  you want to have dinner together!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值