代理设计模式--静态代理

设计模式:解决问题的套路
 代理设计模式:
    a. 静态代理 
              案例:
              我们通过代理商买电脑, 代理商通过联想公司买电脑
              设计到了两个对象:
              代理设计模式是基于接口的,把需要定义方法都定义在接口中
                     代理商对象:
                     联想公司对象:
    b.动态代理

案例分析

接口文档:代理商和被代理商都有的方法

/*
 * 代理商 和 联想公司 都有的方法
 */
public interface ComputerInterface {
    //卖电脑
    public abstract String buyComputer();
    //免费维修
    public abstract void repair();
}

被代理对象

/*
 * 被代理类,电脑公司
 */
public class ComputerCompany implements ComputerInterface{

    @Override
    public String buyComputer() {
        // TODO Auto-generated method stub
        return "Y4500-1T电脑,3888$";
    }

    @Override
    public void repair() {
        // TODO Auto-generated method stub
        System.out.println("免费的 修好了....");
    }

}
public class SmallComputerCompany implements ComputerInterface{

    @Override
    public String buyComputer() {
        // TODO Auto-generated method stub
        return "迷你掌上电脑,19999$";
    }

    @Override
    public void repair() {
        // TODO Auto-generated method stub
        System.out.println("需要五块钱维修费..");
    }

}

代理对象

 
/*
 * 代理类:经销商
 */
public class ProxyPerson implements ComputerInterface{
    
    private ComputerInterface lianxiang;
    
    
        
    public ProxyPerson(ComputerInterface lianxiang) {
        this.lianxiang = lianxiang;
    }

    @Override
    public String buyComputer() {
        // TODO Auto-generated method stub
        return "鼠标,键盘,电脑包,u盘,操作系统,3000$ + "+lianxiang.buyComputer();
    }

    @Override
    public void repair() {
        // TODO Auto-generated method stub
        System.out.println("需要运费1000块");
        lianxiang.repair();
        System.out.println("再给500块保管费");
        System.out.println("再给100块运费");
    }

}

 验证

 
 
/*
 * 设计模式:解决问题的套路
 *
 * 代理设计模式:
 *   a.静态代理 
 *    案例:
 *    我们通过代理商买电脑, 代理商通过联想公司买电脑
 *    设计到了两个对象:
 *    代理设计模式是基于接口的,把需要定义方法都定义在接口中
 *     代理商对象:
 *     联想公司对象:
 *    
 *   b.动态代理
 *
 */
public class ProxyDemo {
 
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //测试
  //被代理公司
  ComputerCompany lianxiang = new ComputerCompany();
  SmallComputerCompany smalllx = new SmallComputerCompany();
  //代理对象
  ProxyPerson pp = new ProxyPerson(smalllx);
  //买电脑
  
  String s =  pp.buyComputer();
  System.out.println(s);
  
  pp.repair();
  
  
 }
 
 
}
 

猜你喜欢

转载自www.cnblogs.com/zsj03180204/p/11070701.html