读书人

单例与署理模式

发布时间: 2012-09-09 09:27:54 作者: rapoo

单例与代理模式

单例与代理模式
? 单例模式
??? 1、私有的静态类变量
????? public class Test {
??????? private static Test test = new Test();
??????? private Test(){}
??????? private static Test getTest(){
????????? return test;
??????? }
????? }
??? 2、在一个方法里实例化对象
????? public class Test{
??????? private static Test test;
??????? private Test(){}
??????? private static synchronized Test getTest(){
????????? if(test == null){
??????????? test = new Test();
????????? }
????????? return test;
??????? }
????? }
? 代理模式
??? 1、静态代理模式
????? public class Proty implements Inter {
??????? private Inter inter;
??????? public Proty(Inter inter) {
????????? this.inter = inter;
??????? }
??????? @Override
??????? public void play() throws Exception {
????????? System.out.println("进来了");
????????? inter.play();
??????? }
????? }
??? 2、动态代理模式
????? package com.lovo.dao.imp;
????? import java.lang.reflect.InvocationHandler;
????? import java.lang.reflect.Method;
????? import java.lang.reflect.Proxy;
????? import org.hibernate.Session;
????? import com.lovo.util.HibernateSessionFactory;
????? public class MyProxy implements InvocationHandler {
??????? private BaseDao dao;
??????? public MyProxy(BaseDao dao) {
????????? this.dao = dao;
??????? }
??????? public Object getObject(){
????????? Object obj = Proxy.newProxyInstance(dao.getClass().getClassLoader(), dao.getClass().getInterfaces(), this);
????????? return obj;
??????? }
??????? @Override
??????? public Object invoke(Object arg0, Method arg1, Object[] arg2)
????????? throws Throwable {
????????? Object object = null;
????????? Session session = HibernateSessionFactory.getSession();
????????? session.beginTransaction();
????????? dao.setSession(session);
????????? try {
??????????? object = arg1.invoke(dao, arg2);
??????????? session.getTransaction().commit();
????????? } catch (Exception e) {
??????????? e.printStackTrace();
??????????? session.getTransaction().rollback();
????????? }finally{
??????????? session.close();
????????? }
????????? return object;
??????? }
????? }
??? 备注:代理方法只是一种服务和正常的业务逻辑没有关系式一种横切面的关注点;其次代理模式需要通过接口来调方法

读书人网 >软件架构设计

热点推荐