Now I got your point. Actually, you're right about that. The factory pattern somehow violates the open-closed principle, but its violation is not the worst and you can deal with it if you apply the pattern correctly. You can't always apply the principle as the book says. But you can always try to reduce and control the violation.
Imagine if the photo has open, close, and share functions.
classPhotoViewer{voiddoSomethingToPhoto(Stringtype,Stringaction){if(type=="JPEG"){if(action=="open"){// do something}elseif(action=="close"){// do something}elseif(action=="share"){// doe something}}elseif(type=="PNG"){if(action=="open"){// do something}elseif(action=="close"){// do something}elseif(action=="share"){// doe something}}else{if(action=="open"){// do something}elseif(action=="close"){// do something}elseif(action=="share"){// doe something}}}}
You can see that this is one of the worst things you can do to add those functionalities. So, the correct way is to create a Photo interface and force every new photo type to implement. Even if that shifted the violation to use the Factory pattern. You can control its behavior and limit the problems to the creation only. Because it's a well-known design pattern.
I hope I answered your question clearly and I will try to edit the example to become clearer. Also, try to read this article it's useful and talks about that:
Now I got your point. Actually, you're right about that. The factory pattern somehow violates the open-closed principle, but its violation is not the worst and you can deal with it if you apply the pattern correctly. You can't always apply the principle as the book says. But you can always try to reduce and control the violation.
Imagine if the photo has open, close, and share functions.
You can see that this is one of the worst things you can do to add those functionalities. So, the correct way is to create a Photo interface and force every new photo type to implement. Even if that shifted the violation to use the Factory pattern. You can control its behavior and limit the problems to the creation only. Because it's a well-known design pattern.
I hope I answered your question clearly and I will try to edit the example to become clearer. Also, try to read this article it's useful and talks about that:
sergeyzhuk.me/2018/01/25/factory-m...
Drop the if and generate the class name, quick cut:
(Untested PHP, but I’m mobile right now)