CSDN博客

img switzerland

透过工厂类讲单例模式

发表于2008/10/2 11:19:00  348人阅读

/**

 * 工厂类,负责动态装载UserDao4MySqlImpl

 */

public class UserDaoFactory {

         //利用一个静态变量来记录UserDaoFactory唯一实例

         private static UserDaoFactory instance;

        

         private UserDao userDao;

        

         //私有的构造器,只有UserDaoFactory类内部才可以调用构造器

         private UserDaoFactory() {

                   //可以从配置文件中动态装载UserDao4MySqlImpl实现类,便于灵活更换

                   userDao = new UserDao4MySqlImpl();

                  

                   //DB改为Oracle,只需重设userDao,仅修改此处,灵活性好

                   userDao = new UserDao4OracleImpl();

         }

        

         /**

         *synchronized关键字迫使每个线程在进入getInstance()方法之前,

         *要先等候别的线程离开该方法.不会有两个线程同时进入这个方法.

         */

         public static synchronized UserDaoFactory getInstance() {

                   if (instance == null) {

                            instance = new UserDaoFactory();

                   }

                   return instance;

         }

        

         /**

          * 创建UserDao对象

          * @return UserDao UserDao接口

          */

         public UserDao createUserDao() {

                   return userDao;

         }

}

0 0

相关博文

我的热门文章

img
取 消
img