日期:2014-05-17 浏览次数:20695 次
class User { private String name; private int age; public void setName(String name){ this.name=name; } public void setAge(int age){ this.age=age; } public String getName(){ return this.name; } public int getAge(){ return this.age; } } interface UserDAO { public boolean doCreate(User user)throws Exception; } class UserDAOImpl implements UserDAO { private String str=null; public UserDAOImpl(String str){ this.str=str; } public boolean doCreate(User user)throws Exception{ boolean flag=false; try{ System.out.println("真实主题类的数据库增加操作"); }catch(Exception e){ e.printStackTrace(); }finally{ } return flag; } } class UserDAOProxy implements UserDAO { private UserDAOImpl dao=null; private String str=null; //此处其实应该传入一个数据库的连接到真实主题类的,不过这里只是个演示,所有以字符串的形式传了进去 public UserDAOProxy(){ this.str=new String(); this.dao=new UserDAOImpl(this.str); } public boolean doCreate(User user)throws Exception{ boolean flag=true; System.out.println("代理类的操作,打开数据库,同时取得真实主题类的实例去调用真实的数据层操作"); try{ this.dao.doCreate(user); }catch(Exception e){ e.printStackTrace(); }finally{ System.out.println("代理类的操作,调用完真实主题类的操作,同时关闭数据库"); } return flag; } } class UserDAOFactory { public static UserDAO getUserDAONewInstance(){ System.out.println("通过工厂类取得代理类的实例去调用代理类的操作。"); return new UserDAOProxy(); } } public class FactoryDemo { public static void main(String args[])throws Exception{ User user=new User(); user.setName("jhjjs"); user.setAge(20); UserDAOFactory.getUserDAONewInstance().doCreate(user); } }