问题
I have seen this implementation in Room database.
There is an abstract class AppDatabase -
@Database(entities = {Task.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract TaskDao taskDao();
}
But when you create an Object of this AppDatabase class, you do something like this -
AppDatabase appDatabase =
Room.databaseBuilder(context, AppDatabase.class, "something").build();
My questions are -
How can you pass an Abstract class directly like this without the Override methods defined ?
Like, normally we don't use and pass abstract classes like that, if you do something like this in IDE, it throws an error.
Which design pattern is this and how Room handles this type of things internally ?
回答1:
1) The idea of using abstract classes is to have a sort of contract between the developer and room. We use abstract classes (or interfaces) because the implementation of those Dao methods will not be provided by us the developers but by Room itself.
2) It is a Builder design pattern, this design pattern is generally used when we have many options for how we'd like to create our final object and the pattern provides a more maintainable api for doing so. The example you provide is just a basic initialization of the database, but we can actually set many params whilst building the database class. For instance we can add the following option when building the database in order to tell it to delete everything and start again in case our database schema changes:
.fallbackToDestructiveMigration()
How Rooms handles thing internally is a bit of a hard question, but in general terms it is an abstraction layer of SQL apis provided by android itself, it will use your contracts (abstract classes or interfaces) for the Daos and the Database in order to create implementations for all of those abstract methods defined in those classes. Once you've setup everything and built your project the first time, Room will generate a bunch of _Impl classes that will implement those abstract methods. For instance, if you have a UserDao, it will generate a UserDao_Impl class that extends (or implements if you've used an interface) the original UserDao and it will provide those implementations. What it does internally will depend on the method, but it's basically using the SQLite api provided by Android.
来源:https://stackoverflow.com/questions/54386798/how-does-it-work-passing-an-abstract-class-as-parameter-in-room-database-builde