https://github.com/sheracore/DesignPatterns
class Journal:
def __init__(self):
self.entries = []
self.count = 0
def add_entry(self, text):
self.entries.append(f"{self.count}: {text}")
self.count += 1
def remove_entry(self, pos):
del self.entries[pos]
def __str__(self):
return "\n".join(self.entries)
# break SRP
def save(self, filename):
file = open(filename, "w")
file.write(str(self))
file.close()
def load(self, filename):
pass
def load_from_web(self, uri):
pass
class PersistenceManager:
def save_to_file(journal, filename):
file = open(filename, "w")
file.write(str(journal))
file.close()
def load(self, filename):
pass
def load_from_web(self, uri):
pass
j = Journal()
j.add_entry("I cried today.")
j.add_entry("I ate a bug.")
print(f"Journal entries:\n{j}\n")
p = PersistenceManager()
file = r'c:\temp\journal.txt'
p.save_to_file(j, file)
# verify!
with open(file) as fh:
print(fh.read())
The Open-Closed Principle (OCP) is one of the SOLID principles that emphasizes:
"A class should be open for extension, but closed for modification."
This means that you should be able to add new functionality to a module, class, or function without altering its existing code. The principle promotes the use of abstractions, polymorphism, and other techniques to extend behavior while keeping the existing implementation intact.