首页 > 代码库 > 接口实际应用-工厂代理模式

接口实际应用-工厂代理模式

 1 package cn.demo; 2 interface Subject{ 3     public void get(); 4 } 5 class RealSubject implements Subject{ 6     public void get(){ 7         System.out.println("吃饭"); 8     }  9 }10 class Factory{11     public static Subject getInstance(String charName){12         if("real".equals(charName)){13             return new RealSubject();14         }15         return null;16     }17 }18 class Proxy implements Subject{19     private Subject sub;20     public Proxy(){21         this.sub = Factory.getInstance("real");22     }23     public void prepare(){24         System.out.println("饭前洗手");25     }26     public void get(){27         this.prepare();28         this.sub.get();29         this.after();30     }31     public void after(){32         System.out.println("收拾餐桌");33     }34 }35 public class Test{36     public static void main(String args[]){37         Subject s =new Proxy();38         s.get();39     }40 }

结果:

饭前洗手
吃饭
收拾餐桌

接口实际应用-工厂代理模式