1.概念

  • 高层模块不应该依赖底层模块,这两个都应该依赖抽象
  • 抽象不应该依赖细节,细节应该依赖抽象
  • 什么叫高层次模型,通常所说的客户端就是高层次模型,而其调用的接口即是低层次的模型,这句话也可以说,客户端不应该依赖于接口的具体,而是依赖于接口的抽象。

    2.里氏代换原则

  • 子类型可以替换调它们的父类型

    3. 针对抽象编程

  • 程序中所有的依赖关系都是终止于抽象类或接口

    4.代码实现

    ``` import abc

class Car(object): metaclass = abc.ABCMeta

  1. @abc.abstractmethod
  2. def car_run(self, *args, **kwargs):
  3. pass
  4. @abc.abstractmethod
  5. def car_turn(self, *args, **kwargs):
  6. pass
  7. @abc.abstractmethod
  8. def car_stop(self, *args, **kwargs):
  9. pass

class Ford(Car): def init(self): self.type = ‘ford’

  1. def car_run(self):
  2. print('%s is running' % self.type)
  3. def car_turn(self):
  4. print('%s is turning' % self.type)
  5. def car_stop(self):
  6. print('%s is stopping' % self.type)

class Buick(Car): def init(self): self.type = ‘buick’

  1. def car_run(self):
  2. print('%s is running' % self.type)
  3. def car_turn(self):
  4. print('%s is turning' % self.type)
  5. def car_stop(self):
  6. print('%s is stopping' % self.type)

class Cadillac(Car): def init(self): self.type = ‘cadillac’

  1. def car_run(self):
  2. print('%s is running' % self.type)
  3. def car_turn(self):
  4. print('%s is turning' % self.type)
  5. def car_stop(self):
  6. print('%s is stopping' % self.type)

class AutoSystem(object):

  1. def __init__(self, car):
  2. self.car = car
  3. def car_run(self):
  4. self.car.car_run()
  5. def car_turn(self):
  6. self.car.car_turn()
  7. def car_stop(self):
  8. self.car.car_stop()

if name == ‘main‘: ford = Ford() buick = Buick() cadillac = Cadillac() autosystem = AutoSystem(ford) autosystem.car_run() autosystem.car_turn() autosystem.car_stop() autosystem.car = buick print(‘100) autosystem.car_run() autosystem.car_turn() autosystem.car_stop() print(“100) autosystem.car = cadillac autosystem.car_run() autosystem.car_turn() autosystem.car_stop() ```