策略模式--设计模式系列
今天我们写一个鸭子类,首先分析一下鸭子有哪些特征呢?
鸭子:会叫,会游水,会飞,外观
现在有个需求:分两种鸭子,一种是外观是绿头,一种是红头,写下看:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Duck: def quack( self ): print ( '呱呱叫' ) def swim( self ): print ( '我会游泳' ) def display( self ): pass def fly( self ): print ( '我会飞' ) class RedDuck(Duck): def display( self ): print ( '我是红头' ) class GreenDuck(Duck): def display( self ): print ( '我是绿头' ) |
似乎利用派生类,我们很容易就解决了这问题,那现在又有个需求来了:区分开会飞的鸭子和不会飞鸭子
你可能会想:这还不简单,在派生类里重写一下飞的方法就可以了
但是这样,对于不会飞的鸭子本来就不应该有fly这个函数,所以这种解决方式有些不妥!
似乎我们在定义基类时就有些误区,不应该就把某些方法定死了
策略模式:
- 针对接口编程,而不是实现编程
- 分离应用中经常变化的部分
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | class FlyBehavior: '''Interface class:FlyBehavior''' def fly( self ): pass class Flywithwing(FlyBehavior): def fly( self ): print ( 'I can fly' ) class Flynoway(FlyBehavior): def fly( self ): print ( 'I can not fly' ) class Duck: def __init__( self ,flyParam): self .fly_behavior = flyParam def performFly( self ): self .fly_behavior.fly() def swim( self ): print ( '我会游水' ) def display( self ): pass class RedDuck(Duck): def __init__( self ,flyParam = Flynoway()): Duck.__init__( self ,flyParam) def display( self ): print ( '我是红头' ) class GreenDuck(Duck): def __init__( self ,flyParam = Flywithwing()): Duck.__init__( self ,flyParam) def display( self ): print ( '我是绿头' ) g_duck = GreenDuck() g_duck.performFly() g_duck.display() g_duck.swim() r_duck = RedDuck() r_duck.performFly() r_duck.display() r_duck.swim() |
欢迎大家对我的博客内容提出质疑和提问!谢谢
笔者:拍省先生
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步