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