Lets take a downloading example.
You have a Base class FileDownloadModel, and have 3 subclasses AudioFileDownloadModel, VideoFileDownloadModel, and ImageDownloadModel.
You have a DownloadManager that takes a FileDownloadModel input and uses this model's urlToDownload property to download the file.
Later down the line you are told that there is one more model coming but it's of type UserDownloadModel which is a subclass of User, and not FileDownloadModel.
See now it becomes difficult to handle this scenario where you will have to change a lot of code to incorporate downloading methods.
How protocol oriented programming will help you here:
- Create a protocol named DownloadingFileProtocol and add
methods and properties that you need for downloading a file. eg. urlToDownload,
pathToSave, extension etc.
- Implement the same protocol in FileDownloadModel and
UserDownloadModel. The benefit here is that you don't have to change a
lot of code in UserDownloadModel. You will just implement the
methods from the DownloadingFileProtocol.
- If a new entity comes down the line again, you will not
change any code. Rather, you'll just implement the protocol methods.
- And now your DownloadManager can take a
DownloadingFileProtocol as input instead of a specific model. As well, you can now make any model "downloadable" by having it adopt this protocol.