In my application a user would enter a link for an image or a video. According to the type of media (image, video or Pin from Pinterest) the app will determine how to display a thumbnail of the entered media link, for example :
If link entered is a video, generate thumbnail from video then generate an HTML code snippet that will display the thumbnail.
If an image, reduce the size and return HTML snippet with the smaller image as a thumbnail.
If Pinterest link, generate embed a Pinterest HTML code.
Whatever type of link it is, it will probably have a prepThumbnail()
method which will return the thumbnail image and a getThumbnailSnippet()
which will return the HTML code with an image link.
To avoid using if statements and to be able to grow the types of media links, I've decided to use the
State Pattern
where I would capture the link, whatever the media type is, as a MediaLink
object/context and within that object I can set the state at run time to either HasImage
state/object that has the methods prepThumbnail()
and getThumbnailSnippet()
which are compatible with an image link and produce the thumbnail and the code snippet that I will embed.
So I just need to add a HasVideo
state , HasPin
state.
I was also thinking about the
Factory Method or Abstract Factory pattern
where I create an ImageLinkFactory
, VideoLinkFactory
, PinterestFactory
and have each create the type of `MediaLink that I need.
The state pattern would not be my first choice, as you don't need to change any state for handling different file types, except for example the user enters different types of files in a specific order or some scenario like that.
The factory pattern indeed could help you instantiating your objects, but that's something you might not initially need, as you could also just instantiate the implementation for all file types once at startup.
You might want to use the strategy pattern, where your strategy interface contains the common methods you described, and your strategy implementations contain the file type specific implementations thereof. When bootstrapping your application you could register those implementations for the associated types they should handle. This makes it very easy to add support for new types, you would just need to create a new strategy implementation and register it.
You can find real-world usage of design patterns in a lot of open source projects, e.g. in Java.