学习笔记:方法增强

来源:互联网 发布:光子嫩肤 知乎 编辑:程序博客网 时间:2024/05/16 09:16

某个类的方法需要增强的时候,有三种方法

1、写一个子类,覆盖该方法
2、写一个包装类,增强该方法
3、用动态代理,返回一个代理对象出去,拦截该方法的调用,对该方法进行增强


在学习数据库连接池的时候,对数据库的连接放在池中,当程序获取的connection使用完,调用close方法,会将连接交还给数据库,而我们需要将它还给连接池,connection的close方法需要增强。


第一个方法,写一个connection的子类,重写close方法:

该增强方法这里不能使用,因为原connection的创建由数据库驱动完成,其中包含有信息,而创建的子类由自己创建,缺少一些信息,不能完成原connection的功能。

该方法适用于不包含某些必要信息的类的增强。


第二个方法,用包装设计模式对某个对象进行增强:

1、写一个类,实现与被增强对象(mysql的connection)相同的接口
2、定义一个变量,指向被增强对象
3、定义一个构造方法,接收被增强对象
4、覆盖想增强的方法
5、对于不想增强的方法,直接调用被增强对象的方法

class MyConnection implements Connection{private Connection conn;private List pool;public MyConnection(Connection conn,List pool){this.conn = conn;this.pool = pool;}public void close() throws SQLException {pool.add(conn);}
该方法实现了connection的close方法的增强,不过缺点是需要写的方法太多。。

public Statement createStatement() throws SQLException {return this.conn.createStatement();}public Statement createStatement(int resultSetType, int resultSetConcurrency)throws SQLException {// TODO Auto-generated method stubreturn null; //需要改成this.conn.createStatement}public Statement createStatement(int resultSetType,int resultSetConcurrency, int resultSetHoldability)throws SQLException {// TODO Auto-generated method stubreturn null;}public boolean getAutoCommit() throws SQLException {// TODO Auto-generated method stubreturn false;}public String getCatalog() throws SQLException {// TODO Auto-generated method stubreturn null;}//还没完!!!!!

第三个方法,用动态代理,返回一个代理对象出去,拦截close方法的调用,对close进行增强:

(只懂个大概。。方老大写的)

public Connection getConnection() throws SQLException {if(list.size()>0){final Connection conn = list.removeFirst();return (Connection) Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler(){public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {if(!method.getName().equals("close")){return method.invoke(conn, args);}else{list.add(conn);return null;}}});}else{throw new RuntimeException("对不起,数据库忙");}}





原创粉丝点击