日期:2014-05-16 浏览次数:20644 次
package strategy; public interface Strategy { public void getConnDB(); }
public class MysqlStrategy implements Strategy { public void getConnDB() { /*try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://localhost/myDB?user=root&password=123456&useUnicode=true&characterEncoding=utf-8"; Connection connection = DriverManager.getConnection(url); } catch (SQLException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }*/ System.out.println("connect MySQL"); } }
public class OracleStrategy implements Strategy { public void getConnDB(){ System.out.println("connect oracle"); } }
public class SQLStrategy implements Strategy{ public void getConnDB(){ System.out.println("connect SQL SERVER"); } }
public class ClientContext { Strategy strategy; public ClientContext(Strategy strategy){ this.strategy=strategy; } public void getConnDB(){ strategy.getConnDB(); } }
public class StrategyTest { public static void main(String[] args) { /** * 策略模式实现对Oracle的连接操作. */ ClientContext occ = new ClientContext(new OracleStrategy()); occ.getConnDB(); /** * 策略模式实现对Mysql的连接操作. */ ClientContext mcc = new ClientContext(new MysqlStrategy()); mcc.getConnDB(); /** * 策略模式实现对SQL Server的连接操作. */ ClientContext scc = new ClientContext(new SQLStrategy()); scc.getConnDB(); } }
public class ProxyDB implements InvocationHandler { private Object target; public ProxyDB(Object target) { this.target = target; } /** * 此处为我们要额外添加的方法 进行日志的打印输出 */ public void printLog() { System.out.println("---------------打印输出点日志----------"); } /** * 代理业务处理器 */ public Object invoke(Object proxy, Method method, Object[] args) throws Exception { printLog(); return method.invoke(this.target, args); } public static void main(String[] args) { /** * * 通过代理模式在连接Mysql前增加日志的打印输出; * */ MysqlStrategy ms = new MysqlStrategy(); ProxyDB proxyCorps = new ProxyDB(ms); Strategy realObject = (Strategy) Proxy.newProxyInstance(ms.getClass() .getClassLoader(), ms.getClass().getInterfaces(), proxyCorps); realObject.getConnDB(); /** * 通过代理模式在连接 Oracle前增加日志的打印输出; * */ OracleStrategy os = new OracleStrategy(); ProxyDB proxyCorps1 = new ProxyDB(os); Strategy realObject1 = (Strategy) Proxy.newProxyInstance(os.getClass() .getClassLoader(), os.getClass().getInterfaces(), proxyCorps1); realObject1.getConnDB(); /** * 通过代理模式在连接 SQL Ser