zoukankan      html  css  js  c++  java
  • java设计模式--代理模式

    代理模式:为其他对象提供一种代理来控制对这个对象的访问。我们来看这样一个简单的例子,现在超市商家不直接把商品交给客户,而是通过一些平台的外卖小哥把商品送到客户手中,此时外卖小哥就起到了代理的作用。代码如下:

    //客户类
    public
    class Customer { public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } //出售商品的代理接口,这样就可以在所有实现这个接口的超市类中都可以使用外卖小哥类(Proxy代理) public interface SaleGoods { void saleWater(); void saleFood(); void saleFruits(); }
    //超市实现代理接口(定义外卖小哥所代表的真实的实体)
    public class SuperMarket implements SaleGoods { Customer customer = null; public SuperMarket(Customer customer){ this.customer = customer; } @Override public void saleWater() { System.out.println(customer.getName() +"购买的水"); } @Override public void saleFood() { System.out.println(customer.getName() +"购买的食物"); } @Override public void saleFruits() { System.out.println(customer.getName() +"购买的水果"); } }
    //外卖小哥实现代理接口
    public class TakeOutBrother implements SaleGoods { SuperMarket superMarket = null; public TakeOutBrother(Customer customer){
        //通过超市的引用调用超市的方法
    this.superMarket = new SuperMarket(customer); } @Override public void saleWater() {
         //调用超市的方法 superMarket.saleWater(); } @Override
    public void saleFood() { superMarket.saleFood(); } @Override public void saleFruits() { superMarket.saleFruits(); } } public class Test { public static void main(String[] args) { Customer customer = new Customer(); customer.setName("zhangsan"); TakeOutBrother takeOutBrother = new TakeOutBrother(customer); takeOutBrother.saleFood(); takeOutBrother.saleFruits(); takeOutBrother.saleWater(); } }
  • 相关阅读:
    希腊字母写法
    The ASP.NET MVC request processing line
    lambda aggregation
    UVA 10763 Foreign Exchange
    UVA 10624 Super Number
    UVA 10041 Vito's Family
    UVA 10340 All in All
    UVA 10026 Shoemaker's Problem
    HDU 3683 Gomoku
    UVA 11210 Chinese Mahjong
  • 原文地址:https://www.cnblogs.com/yimengyizhen/p/11094497.html
Copyright © 2011-2022 走看看