https://yq.aliyun.com/articles/45638
开放封闭原则,是面向对象编程的核心,也是其他五大设计原则实现的终极目标。只有对抽象编程,而不是对具体编程才是遵循了开放封闭原则。
开放:指的是软件对扩展开放。
封闭:指的是软件对修改封闭。
即软件增加或改变需求是通过扩展来到,而不是通过修改来实现的。即一个类定型后尽量不要去修改。而是通过增加新类来满足需求。
举例:银行的统一叫号系统。代码如下
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 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类中的方法分别拆分为类。这样就符合了单一职责原则。同时增加功能只需增加类就行了。避免了通过修改现有类来增加功能