I want to display different type of stories in a news feed using a RecyclerView
. For example one story could have a template of how the weather changed. So the JSON data would contain the day, temperature etc.
I download the stories as JSON from the database and parse them. Currently, I'm storing the parsed JSON objects in a List<FeedStoryContainer>
. FeedStoryContainer
has two properties, an int
representing the type and an Object
containing the data. When it comes time to bind the data I cast the Object
into the correct story type which in based on the int
type. Is this approach okay?
In my opinion it would be better that your story types should have the same base and api. Keep them in List< StoryBase > with the same api. Casting of object depending of it type ( int ) is some solution but sooner or later it won't help. Better is to use polymorphism.
class Story
{
void apply( Viewer viewer )
{
System.out.println( "Default implementation" )
}
}
class News extends Story
{
void apply( Viewer viewer )
{
viewer.setTextBody( this.title + " " + this.content );
}
}
class Wheather extends Story
{
void apply( Viewer viewer )
{
viewer.setTextBody( this.title + " " + this.temperature );
}
}
code
List< Story > list;
for( Story story : list )
{
story.apply( this );
}
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.