Singleton Pattern

class Logger(object):
_instance = None
def __init__(self):
raise RuntimeError('Error: Call instance() instead')
@classmethod
def instance(cls):
if cls._instance is None:
print('Creating new instance')
cls._instance = cls.__new__(cls)
return cls._instance
def __str__(self):
return "singleton pattern"

try:
l = Logger()
except RuntimeError as err:
print(err)
l = Logger.instance()
print(type(l))
print(l)

Factory Pattern

class CompressionFactory:
compression = {}
def __new__(cls):
cls.compression = {"rar": Rar(), "tar": Tar(), "zip": Zip()}
return cls

@classmethod
def getCompression(cls, method):
return cls.compression[method]

import abc
class File(abc.ABC):
def __init__(self, txt):
self.txt = txt
def __str__(self):
return self.txt


class Compression(abc.ABC):
@abc.abstractmethod
def compress(file):
pass

class Rar:
@staticmethod
def compress(file):
print(f"Rar compresstion {file}")

class Tar:
@staticmethod
def compress(file):
print(f"Tar compresstion {file}")

class Zip:
@staticmethod
def compress(file):
print(f"Zip compresstion {file}")

file = File("Text File")
factory = CompressionFactory()
CompressionFactory.getCompression("rar").compress(file)
CompressionFactory.getCompression("tar").compress(file)
CompressionFactory.getCompression("zip").compress(file)

Proxy Pattern

In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.

In proxy pattern, we create object having original object to interface its functionality to outer world.

import abc
class Greeter(abc.ABC):
@abc.abstractmethod
def greet(self):
pass

class RealGreeter(Greeter):
def __init__(self, name):
self.name = name
def greet(self):
return str("Hello " + self.name)

class GreaterProxy(Greeter):
greeter = None
def greet(cls, name):
# Check if the user is authorized before calling real greater
# Check real greater is available ( resources )

if cls.greeter == None:
cls.greeter = RealGreeter(name)
else:
cls.greeter.name = name
return cls.greeter.greet()

proxy = GreaterProxy()
print(proxy.greet("Chang"))