代理模式:為其他對象提供一種代理來控制對這個對象的訪問。我們來看這樣一個簡單的例子,現在超市商家不直接把商品交給客戶,而是通過一些平臺的外賣小哥把商品送到客戶手中,此時外賣小哥就起到了代理的作用。代碼如下: ...
代理模式:為其他對象提供一種代理來控制對這個對象的訪問。我們來看這樣一個簡單的例子,現在超市商家不直接把商品交給客戶,而是通過一些平臺的外賣小哥把商品送到客戶手中,此時外賣小哥就起到了代理的作用。代碼如下:
//客戶類
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(); } }