Category Archives: Design Pattern

Command Pattern


class Document:
    text = ""
    def __str__(self):
        return self.text

import abc
class DocumentCommand(abc.ABC):
    doc = None
    @abc.abstractmethod
    def execute(self):
        pass
    @abc.abstractmethod
    def undo(self):
        pass

class AddStrCommand(DocumentCommand):
    def __init__(self, doc, txt):
        self.text = txt
        self.doc = doc
    def execute(self):
        self.doc.text += self.text
        return self.doc
    def undo(self):
        return DeleteStrCommand(self.doc, self.text).execute()

class DeleteStrCommand(DocumentCommand):
    def __init__(self, doc, txt):
        self.text = txt
        self.doc = doc
    def execute(self):
        idx = self.doc.text.find(self.text)
        if idx == -1:
            return self.doc
        self.doc.text = self.doc.text[:idx]
        return self.doc
    def undo(self):
        return AddStrCommand(self.doc, self.text).execute()

doc = Document()
addingTexts = [AddStrCommand(doc,"hello\n"), AddStrCommand(doc,"My name is Chang\n"),  AddStrCommand(doc,"I hope you have a good day")]
for c in addingTexts:
    c.execute()
print("#"*5)
print(doc)
print("#"*5)
print(addingTexts[-1].undo())
print("#"*5)
print(addingTexts[-1].undo())
print("#"*5)
print("*"*30)
d = DeleteStrCommand(doc,"My name is Chang\n")
print(d.execute())
print("#"*5)
print(d.undo())
print("#"*5)