开放封闭原则,是面向对象编程的核心,也是其余五大设计原则实现的终极目标。只有对抽象编程,而不是对具体编程才是遵循了开放封闭原则。编程
开放:指的是软件对扩展开放。设计
封闭:指的是软件对修改封闭。code
即软件增长或改变需求是经过扩展来到,而不是经过修改来实现的。即一个类定型后尽可能不要去修改。而是经过增长新类来知足需求。对象
举例:银行的统一叫号系统。代码以下it
class BankProcess(object):
def __init__(self):
pass
def deposite(self):
print('deposite')
def withdraw(self):
print('withdraw')
class Customer(object):
def __init__(self, type):
self.type = type
class Client(object):
def __init__(self, customer):
self.customer = customer
self.bankprocess = BankProcess()
def process(self):
if self.customer.type == 'deposite':
self.bankprocess.deposite()
elif self.customer.type == 'withdraw':
self.bankprocess.withdraw()
else:
pass
if __name__ == '__main__':
customer = Customer('withdraw')
client = Client(customer)
client.process()
customer.type = 'deposite'
client.process()
结果以下面向对象编程
withdraw
deposite
上面的例子不符合开放封闭原则,也不符合单一职责原则。若是想增长转帐功能,类bankprocess必须被修改,这就违法了开放封闭原则。同时类bankprocess功能过多,也不符合单一职责原则。class
实现符合开放封闭原则的代码cli
class DepoBankProcess(object):
def __init__(self):
pass
def deposite(self):
print('deposite')
class WitBankProcess(object):
def __init__(self):
pass
def withdraw(self):
print('withdraw')
class Customer(object):
def __init__(self, type):
self.type = type
class Client(object):
def __init__(self, customer):
self.customer = customer
self.bankprocess = None
def process(self):
if self.customer.type == 'deposite':
self.bankprocess = DepoBankProcess()
self.bankprocess.deposite()
elif self.customer.type == 'withdraw':
self.bankprocess = WitBankProcess()
self.bankprocess.withdraw()
else:
pass
if __name__ == '__main__':
customer = Customer('withdraw')
client = Client(customer)
client.process()
customer.type = 'deposite'
client.process()
结果以下扩展
withdraw
deposite
上述代码原bankprocess类中的方法分别拆分为类。这样就符合了单一职责原则。同时增长功能只需增长类就好了。避免了经过修改现有类来增长功能