您的位置:首页 > 编程语言 > Java开发

Java Spring重要模式

2016-05-24 10:59 232 查看
单列模式:

public class A{
private A(){};
private static A a;
public static A getA(){
if(a == null){
synchronized(A.class){
if(a == null){
a = new A();
}
}
}
return a;
}
}


工厂模式:

public class Factory {
private static Properties pro = new Properties();
private static Map map = new HashMap();
static{
try {
InputStreamin = Factory.class.getResourceAsStream("/info.txt");
pro.load(in);
}  catch (IOException e) {
e.printStackTrace();
}
}

public static Object getBean(String key){
if(map.containsKey(key)){//判断map中是否存在键
returnmap.get(key);
}

synchronized(map) {
if(!map.containsKey(key)){
StringclassPath = pro.getProperty(key);
try {
Class c =Class.forName(classPath);
Object obj =c.newInstance();

map.put(key,obj);
returnobj;
} catch(Exception e) {
e.printStackTrace();
}
}
else{
returnmap.get(key);
}
}
returnnull;
}
}


代理模式:

public class DaoProxy implements InvocationHandler{
private Object target;
private static SessionFactory factory;
static{
Configuration cfg = new Configuration().configure();
ServiceRegistry r = newServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
factory =cfg.buildSessionFactory(r);
}

public DaoProxy(Object target){
this.target= target;
}
public Object getProxy(){
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throwsThrowable {
Sessionsession = factory.openSession();
session.beginTransaction();

Object returnObj = null;
try{
//得到目标对象的setSession方法对象
Method m =target.getClass().getMethod("setSession", Session.class);
//执行setSession(),完成session属性的初始化
m.invoke(target, session);

//执行目标对象的目标方法,得到执行方法后的返回值
returnObj =method.invoke(target, args);

session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
session.close();
}
returnreturnObj;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息