!\2. CREATIONAL DESIGN PATTERNS\ 0:07:22 1. Singleton 0:22:24 2. Factory method 0:32:20 3. Abstract factory 0:43:04 4. Builder 0:54:46 5. Prototype !\3. STRUCTURAL DESIGN PATTERNS 1:04:05 1. Adapter 1:15:23 2. Bridge 1:24:00 3. Composite 1:32:38 4. Decorator 1:43:14 5. Facade 1:52:49 6. Flyweight 2:06:00 7. Proxy !\4. BEHAVIOURAL DESIGN PATTERNS 2:16:40 1. Chain of responsibility 2:30:27 2. Command 2:40:12 3. Interpreter 2:52:34 4. Iterator 3:00:08 5. Mediator 3:08:15 6. Memento 3:17:20 7. Observer 3:33:56 8. State
class Logger:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Logger, cls).__new__(cls)
cls._instance.log_file = "app.log"
cls._instance.messages = []
return cls._instance
def log(self, message):
self.messages.append(message)
print(f"Logging: {message}")
# note there is no __init__, it is singleton pattern
from abc import ABC, abstractmethod
class Document(ABC):
@abstractmethod
def open(self): pass
@abstractmethod
def save(self): pass
class Application(ABC):
def new_document(self):
doc = self._create_document()
doc.open()
return doc
@abstractmethod
def _create_document(self) -> Document: pass
class TextEditorApp(Application):
def _create_document(self) -> Document:
return TextDocument()
# note the ABC, abstract method to realize factory pattern. # All documents guarantee open() and save() methods, factory method makes codes more flexible and maintainable.
SOLID Principles
- Single Responsibility Principle (SRP): A class should have only one reason to change
- Open/Closed Principle (OCP): Open for extension, closed for modification
- Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types
- Interface Segregation Principle (ISP): Clients shouldn’t be forced to depend on methods they don’t use
- Dependency Inversion Principle (DIP): Depend on abstractions, not concretions
Other Important Principles
- DRY (Don’t Repeat Yourself): Avoid code duplication
- KISS (Keep It Simple, Stupid): Prefer simplicity over complexity
- Law of Demeter: Minimize coupling between objects
- Separation of Concerns: Each class has a single, well-defined responsibility