Skip to content

Instantly share code, notes, and snippets.

@diegomrodz
Last active August 29, 2015 14:06
Show Gist options
  • Save diegomrodz/8b923d0d1a85731ecd20 to your computer and use it in GitHub Desktop.
Save diegomrodz/8b923d0d1a85731ecd20 to your computer and use it in GitHub Desktop.
Padrões de projeto implementados em Python.
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class Janela(object):
def set_title(self, title):
raise NotImplementedError()
def show(self):
raise NotImplementedError()
class MSJanela(Janela):
@overrides(Janela)
def set_title(self, title):
self.title = "MS " + tilte
@overrides(Janela)
def show(self):
print self.title
class MacJanela(Janela):
@overrides(Janela)
def set_title(self, title):
self.title = "Mac " + title
@overrides(Janela)
def show(self):
print self.title
class Botao(object):
def set_text(self, text):
raise NotImplementedError()
def set_click(self, e):
raise NotImplementedError()
class MSBotao(Botao):
@overrides(Botao)
def set_text(self, text):
self.text = text
@overrides(Botao)
def set_click(self, e):
self.on_click = e
class MacBotao(Botao):
@overrides(Botao)
def set_text(self, text):
self.text = text
@overrides(Botao)
def set_click(self, e):
self.on_click = e
class AbstractFactory(object):
def create_janela(self):
raise NotImplementedError()
def create_botao(self):
raise NotImplementedError()
class MSFactory(AbstractFactory):
@overrides(AbstractFactory)
def create_janela(self):
return MSJanela()
@overrides(AbstractFactory)
def create_botao(self):
return MSBotao()
class MacFactory(AbstractFactory):
@overrides(AbstractFactory)
def create_janela(self):
return MacJanela()
@overrides(AbstractFactory)
def create_botao(self):
return MacBotao()
if __name__ == '__main__':
plataforma = "MACOSX"
uifactory = None
if plataforma == "MACOSX":
uifactory = MacFactory()
elif plataforma == "MS":
uifactory = MSFactory()
janela = uifactory.create_janela()
janela.set_title("Foo")
janela.show() # Mac Foo
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class Employee(object):
numero = -1
nome = ""
dept = ""
salario = -1
def create(self):
# ...
return True
def update(self):
# ...
return True
def delete(self):
# ...
return True
def list_all(self):
# ...
return None
def search(self, nr):
# ...
return None
class Funcionario(object):
numero = -1
nome = ""
dept = ""
salario = -1
def criar(self):
# ...
return True
def atualizar(self):
# ...
return True
def deletar(self):
# ...
return True
def listar_funcionarios(self):
# ...
return None
def buscar_por_numero(self, nr):
# ...
return None
class NovoFuncionario(Funcionario):
employee = None
def __init__(self):
if employee == None:
self.employee = Employee()
@overrides(Funcionario)
def criar(self):
self.employee.numero = self.numero
self.employee.nome = self.nome
self.employee.dept = self.dept
self.employee.salario = self.salario
return self.employee.create()
@overrides(Funcionario)
def atualizar(self):
self.employee.numero = self.numero
self.employee.nome = self.nome
self.employee.dept = self.dept
self.employee.salario = self.salario
return self.employee.update()
@overrides(Funcionario)
def deletar(self):
self.employee.numero = self.numero
return self.employee.delete()
@overrides(Funcionario)
def listar_funcionarios(self):
return self.employee.list_all()
@overrides(Funcionario)
def buscar_por_numero(self, nr):
return self.employee.search(nr)
if __name__ == '__main__':
f = NovoFuncionario()
print f.atualizar()
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class ListImplementor(object):
def add_item(self, item, index=None):
raise NotImplementedError()
def remove_item(self, item):
raise NotImplementedError()
def count(self):
raise NotImplementedError()
def get_item(self, index):
raise NotImplementedError()
class OrderedList(ListImplementor):
items = list()
@overrides(ListImplementor)
def add_item(self, item, index=None):
self.items.append(item)
@overrides(ListImplementor)
def remove_item(self, item):
self.items.remove(item)
@overrides(ListImplementor)
def count(self):
return self.items.count()
@overrides(ListImplementor)
def get_item(self, index):
return self.items[index]
class ListAbstraction(object):
def set_implementor(self, impl):
raise NotImplementedError()
def add(self, item, index=None):
raise NotImplementedError()
def remove(self, item):
raise NotImplementedError()
def get(self, index):
raise NotImplementedError()
def count(self):
raise NotImplementedError()
class BaseList(ListAbstraction):
implementor = None
@overrides(ListAbstraction)
def set_implementor(self, impl):
self.implementor = impl
@overrides(ListAbstraction)
def add(self, item, index=None):
self.implementor.add_item(item)
@overrides(ListAbstraction)
def remove(self, item):
self.implementor.remove_item(item)
@overrides(ListAbstraction)
def get(self, index):
return self.implementor.get_item(index)
@overrides(ListAbstraction)
def count(self):
return self.implementor.count()
if __name__ == '__main__':
ls = OrderedList()
base = BaseList()
base.set_implementor(ls)
base.add(42)
print base.get(0)
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class Veiculo(object):
estrutra = None
motor = None
rodas = None
portas = None
class VeiculoBuilder(object):
veiculo = Veiculo()
def builder_estrutura(self):
raise NotImplementedError()
def builder_motor(self):
raise NotImplementedError()
def builder_rodas(self):
raise NotImplementedError()
def builder_portas(self):
raise NotImplementedError()
def get_veiculo(self):
raise NotImplementedError()
class MotoBuilder(VeiculoBuilder):
@overrides(VeiculoBuilder)
def builder_estrutura(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def builder_motor(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def builder_rodas(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def builder_portas(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def get_veiculo(self):
# Regras do Veiculo
return self.veiculo
class CarroBuilder(VeiculoBuilder):
@overrides(VeiculoBuilder)
def builder_estrutura(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def builder_motor(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def builder_rodas(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def builder_portas(self):
# Regras do Veiculo
return True
@overrides(VeiculoBuilder)
def get_veiculo(self):
# Regras do Veiculo
return self.veiculo
class GeradorVeiculo(object):
veiculoBuilder = None
def __init__(self, veiculoBuilder):
if isinstance(veiculoBuilder, VeiculoBuilder):
self.veiculoBuilder = veiculoBuilder
else:
raise Error()
def gerar_veiculo(self):
self.veiculoBuilder.builder_estrutura()
self.veiculoBuilder.builder_motor()
self.veiculoBuilder.builder_rodas()
self.veiculoBuilder.builder_portas()
return self.veiculoBuilder.get_veiculo()
if __name__ == "__main__":
gerador = GeradorVeiculo(CarroBuilder())
veiculo = gerador.gerar_veiculo()
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class AbstractEmployee(object):
nome = None
salario = None
leaf = True
def add(self, e):
raise NotImplementedError()
def remove(self, e):
raise NotImplementedError()
def subordinados(self):
raise NotImplementedError()
def get_child(self, s):
raise NotImplementedError()
def get_salarios(self, s):
raise NotImplementedError()
class Employee(AbstractEmployee):
def __init__(self, nome, salario):
self.nome = nome
self.salario = salario
@overrides(AbstractEmployee)
def add(self, e):
raise NotImplementedError("Employee can not add another component")
@overrides(AbstractEmployee)
def remove(self, e):
raise NotImplementedError("Employee can not remove another component")
@overrides(AbstractEmployee)
def subordinados(self):
return None
@overrides(AbstractEmployee)
def get_child(self, s):
return None
@overrides(AbstractEmployee)
def get_salarios(self):
return self.salario
class Boss(AbstractEmployee):
def __init__(self, nome, salario):
self.nome = nome
self.salario = salario
self.subordinados = []
@overrides(AbstractEmployee)
def add(self, e):
self.subordinados.append(e)
@overrides(AbstractEmployee)
def remove(self, e):
self.subordinados.remove(e)
@overrides(AbstractEmployee)
def subordinados(self):
return self.subordinados;
@overrides(AbstractEmployee)
def get_child(self, s):
for e in self.subordinados:
if e.nome == s:
return e
return None
@overrides(AbstractEmployee)
def get_salarios(self):
soma = self.salario
for s in self.subordinados:
soma += s.get_salarios()
return soma
if __name__ == '__main__':
ceo = Boss('Presidente', 200000)
ceo.add(Boss('Chefe Mkt', 100000))
ceo.add(Boss('Chefe Ven', 100000))
ceo.get_child('Chefe Mkt').add(Employee('Func Mkt 1', 5000))
ceo.get_child('Chefe Mkt').add(Employee('Func Mkt 2', 5000))
ceo.get_child('Chefe Ven').add(Employee('Func Ven 1', 5000))
print(ceo.get_salarios())
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class Turma(object):
idTurma = None
nome = None
def salvar(self):
raise NotImplementedError()
def alterar(self):
raise NotImplementedError()
def excluir(self):
raise NotImplementedError()
class TurmaBasica(Turma):
@overrides(Turma)
def salvar(self):
return False
@overrides(Turma)
def alterar(self):
return False
@overrides(Turma)
def excluir(self):
return False
class DecoradorTurma(Turma):
def __init__(self, t):
self.turma = t
@overrides(Turma)
def salvar(self):
raise NotImplementedError()
@overrides(Turma)
def alterar(self):
raise NotImplementedError()
@overrides(Turma)
def excluir(self):
raise NotImplementedError()
class TurmaTemporaria(DecoradorTurma):
contrato = None
def __init__(self, t):
super.__init__(self, t)
@overrides(DecoradorTurma)
def salvar(self):
return self.turma.salvar()
@overrides(DecoradorTurma)
def alterar(self):
return self.turma.alterar()
@overrides(DecoradorTurma)
def excluir(self):
return self.turma.excluir()
if __name__ == '__main__':
turma = TurmaBasica()
turma.idTurma = 1
turma.nome = "Turma temporária"
tempTurma = TurmaTemporaria(turma)
print(tempTurma.salvar())
class Pedido(object):
numero = None
class Estoque(object):
def reservar_pedido(self, p):
return True
def liberar_estoque(self, p):
return True
class Fiscal(object):
def calc_impostos(self, p):
return 42
def pedido_cancelado(self, p):
return True
class Financeiro(object):
def recebibo(self, p):
return True
def devolver_valores(self, p):
return True
class PedidoFacade(object):
estoque = None
financeiro = None
fiscal = None
def __init__(self, e, fn, fs):
self.estoque = e
self.financeiro = fn
self.fiscal = fs
def efetivar_pedido(self, p):
self.estoque.reservar_pedido(p)
self.financeiro.recebibo(p)
self.fiscal.calc_impostos(p)
return True
def cancelar_pedido(self, p):
self.estoque.liberar_estoque(p)
self.financeiro.devolver_valores(p)
self.fiscal.pedido_cancelado(p)
return True
if __name__ == '__init__':
p = Pedido()
p.numero = 1
e = Estoque()
fn = Financeiro()
fs = Fiscal()
facade = PedidoFacade(e, fn, fs)
print(facade.efetivar_pedido(p))
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class IBanco(object):
def salvar(self):
raise NotImplementedError()
def alterar(self):
raise NotImplementedError()
def buscar(self):
raise NotImplementedError()
def excluir(self):
raise NotImplementedError()
class BancoOracle(IBanco):
@overrides(IBanco)
def salvar(self):
return False
@overrides(IBanco)
def alterar(self):
return False
@overrides(IBanco)
def buscar(self):
return None
@overrides(IBanco)
def excluir(self):
return False
class BancoMySql(IBanco):
@overrides(IBanco)
def salvar(self):
return False
@overrides(IBanco)
def alterar(self):
return False
@overrides(IBanco)
def buscar(self):
return None
@overrides(IBanco)
def excluir(self):
return False
class BancoFactory(object):
ORACLE = 0
MYSQL = 1
@staticmethod
def get_banco(n):
if n == BancoFactory.ORACLE:
return BancoOracle()
elif n == BancoFactory.MYSQL:
return BancoMySql()
else:
raise Exception('Argumento invalido.')
if __name__ == '__main__':
banco = BancoFactory.get_banco(BancoFactory.ORACLE)
print(banco.salvar())
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class ILogger(object):
def log(self, message):
raise NotImplementedError()
class XMLLogger(ILogger):
@overrides(ILogger)
def log(self, message):
print "XML Logger: " + message
class ReadFileLogger(ILogger):
@overrides(ILogger)
def log(self, message):
print "Read File Logger: " + message
class WriteFileLogger(ILogger):
@overrides(ILogger)
def log(self, message):
print "Write File Logger: " + message
class ConnectionLogger(ILogger):
@overrides(ILogger)
def log(self, message):
print "Connection Logger: " + message
class AbstractCreator(object):
def create_logger(self):
raise NotImplementedError()
def get_logger(self):
return self.create_logger()
class XMLLoggerCreator(AbstractCreator):
@overrides(AbstractCreator)
def create_logger(self):
return XMLLogger()
class ReadFileLoggerCreator(AbstractCreator):
@overrides(AbstractCreator)
def create_logger(self):
return ReadFileLogger()
class WriteFileLoggerCreator(AbstractCreator):
@overrides(AbstractCreator)
def create_logger(self):
return WriteFileLogger()
class ConnectionLoggerCreator(AbstractCreator):
@overrides(AbstractCreator)
def create_logger(self):
return ConnectionLogger()
if __name__ == '__main__':
logger = ConnectionLoggerCreator().create_logger()
logger.log("Erro 404.")
class EstadoFlyweight(object):
id = None
nome = None
sigla = None
class Estado(EstadoFlyweight):
def __init__(self, estado):
# queries an db based on the estado arg
self.id = 42
self.estado = estado
self.sigla = 'sp'
class FactoryEstado(object):
estados = {}
@staticmethod
def get_estado(estado):
if not FactoryEstado.estados.has_key(estado):
FactoryEstado.estados[estado] = Estado(estado)
return FactoryEstado.estados[estado]
class Remessa(object):
estado = None
if __name__ == '__main__':
remessa = Remessa()
remessa.estado = FactoryEstado.get_estado('Sao Paulo')
print(remessa.estado.sigla)
class Camera(object):
location = None
instances = {}
def __init__(self, location):
self.location = location
@staticmethod
def set_instance(hardwareId, location):
Camera.instances[hardwareId] = Camera(location)
@staticmethod
def get_instance(hardwareId):
return Camera.instances[hardwareId]
if __name__ == '__main__':
Camera.set_instance(1, 'Foo')
Camera.set_instance(2, 'Bar')
print(Camera.get_instance(1).location)
class Resource(object):
value = None
def reset(self):
self.value = None
class ObjectPool(object):
instance = None
resources = list()
def __init__(self):
if self.instance != None:
raise NotImplemented()
@staticmethod
def get_instance():
if ObjectPool.instance == None:
ObjectPool.instance = ObjectPool()
return ObjectPool.instance
def get_resource(self):
if len(self.resources) > 0:
return self.resources.pop()
else:
return Resource()
def return_resource(self, resource):
resource.reset()
self.resources.append(resource)
if __name__ == '__main__':
pool = ObjectPool.get_instance()
a = pool.get_resource()
b = pool.get_resource()
a.value = 90
b.value = 42
print "a :{0}, b: {1}".format(a.value, b.value)
pool.return_resource(a)
pool.return_resource(b)
a = None
b = None
a = pool.get_resource()
b = pool.get_resource()
print "a :{0}, b: {1}".format(a.value, b.value)
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
class Prototype(object):
def clone(self):
raise NotImplementedError()
class Janela(Prototype):
titulo = None
altura = None
largura = None
def __init__(self, titulo, altura, largura):
self.titulo = titulo
self.largura = largura
self.altura = altura
@overrides(Prototype)
def clone(self):
return self
if __name__ == '__main__':
janela1 = Janela("Foo", 10, 5)
janela2 = janela1.clone()
janela1.titulo = "Bar"
print(janela2.titulo)
class ConfigManager(object):
serverName = None
instance = None
def __init__(self, serverName):
self.serverName = serverName
@staticmethod
def get_instance():
if ConfigManager.instance == None:
ConfigManager.instance = ConfigManager("MACOS")
return ConfigManager.instance
if __name__ == '__main__':
print(ConfigManager.get_instance().serverName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment