Mybatis VFS涉及到的单例模式

静态内部类方式单例模式示例

package com.wjz.mybatis.singleton;

import com.wjz.mybatis.pojo.Person;

/**
 * 静态内部类方式单例模式
 * 
 * @author iss002
 *
 */
public abstract class StaticInnerTest {

    // 私有的静态内部类,只会在newInstance方法中被使用
    private static class PersonHondler {
        // 访问静态内部类的静态字段时静态内部类才会被初始化
        // 类加载机制保证类只加载一次即保证线程安全
        public static final Person person = new Person();
    }

    public static Person newInstance() {
        return PersonHondler.person;
    }

}

VFS涉及的单例模式

public abstract class VFS {

    public static VFS getInstance() {
        return VFSHolder.INSTANCE;
    }

    private static class VFSHolder {
    static final VFS INSTANCE = createVFS();

    /** Singleton instance holder. */
    @SuppressWarnings("unchecked")
    static VFS createVFS() {
          // Try the user implementations first, then the built-ins
          List<Class<? extends VFS>> impls = new ArrayList<Class<? extends VFS>>();
          impls.addAll(USER_IMPLEMENTATIONS);
          impls.addAll(Arrays.asList((Class<? extends VFS>[]) IMPLEMENTATIONS));

          // Try each implementation class until a valid one is found
          VFS vfs = null;
          for (int i = 0; vfs == null || !vfs.isValid(); i++) {
            Class<? extends VFS> impl = impls.get(i);
            try {
              vfs = impl.newInstance();
              if (vfs == null || !vfs.isValid()) {
                if (log.isDebugEnabled()) {
                  log.debug("VFS implementation " + impl.getName() +
                      " is not valid in this environment.");
                }
              }
            } catch (InstantiationException e) {
              log.error("Failed to instantiate " + impl, e);
              return null;
            } catch (IllegalAccessException e) {
              log.error("Failed to instantiate " + impl, e);
              return null;
            }
          }

          if (log.isDebugEnabled()) {
            log.debug("Using VFS adapter " + vfs.getClass().getName());
          }

          return vfs;
        }
    }
}

 

posted @ 2018-11-06 13:13  BINGJJFLY  阅读(910)  评论(0编辑  收藏  举报