Decorator Pattern

import abc
class Shape(abc.ABC):
@abc.abstractmethod
def draw(self):
pass

class Triangle(Shape):
def draw(self):
print("Triangle")

class Circle(Shape):
def draw(self):
print("Circle")

# Decorator was not needed to be inherited from Shape in Python.But you can enforce the draw function
# In Java, inheritance forces to implement parent methods to child Decorators.
class Decorator(Shape):
def __init__(self, shape):
self.shape = shape

class ColorDecorator(Decorator):
def __init__(self, shape, color):
super().__init__(shape)
self.color = color

def draw(self):
print(self.color)
self.shape.draw()
print(self.color)

class PatternDecorator(Decorator):
def __init__(self, shape, pattern):
super().__init__(shape)
self.pattern = pattern

def draw(self):
print(self.pattern)
self.shape.draw()
print(self.pattern)

s = Circle()
s.draw()
cd = ColorDecorator(s, "red")
cd.draw()
pd = PatternDecorator(Triangle(), "Polca dot")
pd.draw()
redPolcaDorCircle = PatternDecorator(cd, "Polca dot")
redPolcaDorCircle.draw()

State Pattern

# Allowing an object to alter behavior
# when its internal state changes so that it appears to change its class

class Phone:
def __init__(self):
self.ring_state = SoundState()
def volumeUp(self):
self.ring_state = self.ring_state.nextVolumeUp()
def volumeDown(self):
self.ring_state = self.ring_state.nextVolumeDown()
def ring(self):
self.ring_state.ring()

import abc

class RingState(abc.ABC):
@abc.abstractmethod
def ring(self):
pass
@abc.abstractmethod
def nextVolumeUp(self):
pass
@abc.abstractmethod
def nextVolumeDown(self):
pass

class SoundState(RingState):
def ring(self):
print("Phone is ringing")
def nextVolumeUp(self):
return self
def nextVolumeDown(self):
return VibrateState()

class VibrateState(RingState):
def ring(self):
print("Phone is vibrating")
def nextVolumeUp(self):
return SoundState()
def nextVolumeDown(self):
return SilentState()

class SilentState(RingState):
def ring(self):
print("Phone is silent")
def nextVolumeUp(self):
return VibrateState()
def nextVolumeDown(self):
return self

phone = Phone()
phone.ring()
phone.volumeDown()
phone.ring()
phone.volumeDown()
phone.ring()
phone.volumeDown()
phone.ring()
phone.volumeUp()
phone.ring()
phone.volumeUp()
phone.ring()

Strategy Pattern

class File:
def __init__(self):
self.strategy = None

def compress(self):
self.strategy.compress()

import abc
class CompressionStrategy(abc.ABC):
@abc.abstractmethod
def compress(cls):
pass

class ZipCompression(CompressionStrategy):
def compress(cls):
print("zip Compression")

class RarCompression(CompressionStrategy):
def compress(cls):
print("rar Compression")

f = File()
f.strategy = ZipCompression()
f.compress()

f.strategy = RarCompression()
f.compress()