Android Room Repository 单例与静态方法

问题描述 投票:0回答:0

我感到很困惑,因为我无法理解使用上下文实例化单例存储库与直接通过上下文访问静态方法之间的区别。

据我所知,由于内存泄漏,在任何类中持有上下文引用都是一种不好的做法,那么为什么这么多人使用第一种单例方法而不是使用按需传递上下文的静态方法?

        public class GameRepository {
         private GamesDao gamesDao;
        
         public GameRepository(Context context) {
            gamesDao = RoomDatabase.getInstance(context).getGamesDao();
          }
        
         public Game getGameForIndex(String game) { 
    return gamesDao.getGameById(game); }
        }

    public class GameRepository {
    
        public static Game getGameForIndex(String game, Context context) {
return RoomDatabase.getInstance(context).getGamesDao().getGameById(game);
        }
    
    }

什么更好? 在构造函数中创建和实例化单例存储库或访问传递上下文的静态方法? 两种方法的优点/缺点是什么?

android repository android-room repository-pattern
© www.soinside.com 2019 - 2024. All rights reserved.