简体   繁体   中英

Is there any benefit of using Singleton class for DiffUtil instead of plain class in RecyclerView?

In this example singleton is used instead of plain class for the DiffUtill callback inside Adapter of RecyclerView. Does this have any advantages over plain class?

Also I would like to know in what case this would be beneficial.

object FlowerDiffCallback : DiffUtil.ItemCallback<Flower>() {
    override fun areItemsTheSame(oldItem: Flower, newItem: Flower): Boolean {
        return oldItem == newItem
    }

    override fun areContentsTheSame(oldItem: Flower, newItem: Flower): Boolean {
        return oldItem.id == newItem.id
    }
}

Full code can be found here

If you do not want to allocate many objects in memory and you want to reuse this object with other adapters. That what Singleton Design Pattern do. In my opinion it is very useless, not testable and not scalable.

If you are gonna use this DiffCallBack multiple times in different Adapters , it is better to use singleton pattern as you no need to create redundant instances of DiffCallback when all it does is to compare flowers. So you can use same instance every where. It do not have major consequences and no memory overhead for holding this object in memory. so you might as well use it as object .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM