|
工厂方法模式:定义一个用于创建对象的接口,由子类来决定实例化哪个类。
代码:
- import pyb
- class LEDx:
- def On(self):
- pass
-
- class LEDR(LEDx):
- def On(self):
- pyb.LED(1).on()
-
- class LEDG(LEDx):
- def On(self):
- pyb.LED(3).on()
-
- class LEDB(LEDx):
- def On(self):
- pyb.LED(4).on()
-
- class LEDxFactory:
- def CreateFactory(self):
- return LEDx()
-
- class LEDRFactory(LEDxFactory):
- def CreateFactory(self):
- return LEDR()
-
- class LEDGFactory(LEDxFactory):
- def CreateFactory(self):
- return LEDG()
-
- class LEDBFactory(LEDxFactory):
- def CreateFactory(self):
- return LEDB()
- if __name__ == "__main__":
- g = LEDGFactory()
- ledg = g.CreateFactory()
- ledg.On()
-
- b = LEDBFactory()
- ledb = b.CreateFactory()
- ledb.On()
复制代码
由一个类派生出多个类,在使用时由工厂接口返回应创建的类来实例化,而不是直接指定要实例化某类。
|
|