Let's say I have a program which can create and delete files. And I have 2 different ways of doing that - either execute external utilities, which already deal with these actions, or implement the creation and deletion from within my program. I want to have the choice of both and select the appropriate one dynamically, during runtime. So I would have interfaces and implementations similar to this:
class IFile:
def create():
pass
def delete():
pass
class ExecFile(IFile):
def create():
# Call an external executable
def delete():
# Call an external executable
class ImplFile(IFile):
def create():
# Implement creation of the file
def delete():
# Implement deletion of the file
This way, I can select either of them during runtime and use it. But what if I decide to create another implementation, which is a mix between ExecFile
and ImplFile
, therefore the create()
function will be the same as in ExecFile
but delete the same as in ImplFile
(or some combination of them). I thought of solving this problem using the command design pattern and do something like the following:
class IFile:
def create():
pass
def delete():
pass
class IFileAction:
def exec():
pass
class ExecCreateFile(IFileAction):
def exec():
# Call an external executable to create file
class ImplCreateFile(IFileAction):
def exec():
# Implement creation of the file
class ExecDeleteFile(IFileAction):
def exec():
# Call an external executable to delete file
class ImplDeleteFile(IFileAction):
def exec():
# Implement deletion of the file
class ExecFile(IFile):
def create():
ExecCreateFile().exec()
def delete():
ExecDeleteFile().exec()
class ImplFileIFile(IFile):
def create():
ImplCreateFile().exec()
def delete():
ImplDeleteFile().exec()
class ExecImplFile(IFile):
def create():
ExecCreateFile().exec()
def delete():
ImplDeleteFile().exec()
Question: Would it be appropriate to use this design pattern in this particular case, or something better could be done? My only concern here is that if the example was more sophisticated, let's say I added an option to get file size, get file owner, etc..., I would end up creating multiple classes of type IFileAction, which basically perform only one action.
P.S This might be a bad example, but couldn't think of anything better. Also, the question does not particularly refer to Python, just used it in order to show a code example.
Aucun commentaire:
Enregistrer un commentaire