同样是水,固态,气态,液态的变化,是由温度引起。

引此为思考状态模式。

  1. from abc import ABCMeta, abstractmethod
  2. # 引入ABCMeta和abstractmethod来定义抽象类和抽象方法
  3.  
  4. """
  5. version 1.0
  6. class Water:
  7.  
  8. def __init__(self, state):
  9. self.__temperature = 25
  10. self.__state = state
  11.  
  12. def set_state(self, state):
  13. self.__state = state
  14.  
  15. def change_state(self, state):
  16. if self.__state:
  17. print(" {} 变为 {}".format(self.__state.get_name(), state.get_name()))
  18.  
  19. else:
  20. print("初始化为{}".format(state.get_name()))
  21. self.__state = state
  22.  
  23. def get_temperature(self):
  24. return self.__temperature
  25.  
  26. def set_temperature(self, temperature):
  27. self.__temperature = temperature
  28. if self.__temperature <= 0:
  29. self.change_state(SolidState("固态"))
  30. elif self.__temperature <= 100:
  31. self.change_state(LiquidState("液态"))
  32. else:
  33. self.change_state(GaseousState("气态"))
  34.  
  35. def rise_temperature(self, step):
  36. self.set_temperature(self.__temperature + step)
  37.  
  38. def reduce_temperature(self, step):
  39. self.set_temperature(self.__temperature - step)
  40.  
  41. def behavior(self):
  42. self.__state.behavior(self)
  43.  
  44. class State:
  45.  
  46. def __init__(self, name):
  47. self.__name = name
  48.  
  49. def get_name(self):
  50. return self.__name
  51.  
  52. @abstractmethod
  53. def behavior(self, water):
  54. pass
  55.  
  56. class SolidState(State):
  57. def __init__(self, name):
  58. super().__init__(name)
  59.  
  60. def behavior(self, water):
  61. print("当前体温: {}".format(str(water.get_temperature())))
  62.  
  63. class LiquidState(State):
  64. def __init__(self, name):
  65. super().__init__(name)
  66.  
  67. def behavior(self, water):
  68. print("当前体温: {}".format(str(water.get_temperature())))
  69.  
  70. class GaseousState(State):
  71. def __init__(self, name):
  72. super().__init__(name)
  73.  
  74. def behavior(self, water):
  75. print("当前体温: {}".format(str(water.get_temperature())))
  76.  
  77. def test_state():
  78. water = Water(LiquidState("液态"))
  79. water.behavior()
  80. water.set_temperature(-4)
  81. water.behavior()
  82. water.rise_temperature(18)
  83. water.behavior()
  84. water.rise_temperature(110)
  85. water.behavior()
  86.  
  87. test_state()
  88. """
  89.  
  90. # version 2.0
  91. class Context(metaclass=ABCMeta):
  92.  
  93. def __init__(self):
  94. self.__states = []
  95. self.__cur_state = None
  96. self.__state_info = 0
  97.  
  98. def add_state(self, state):
  99. if state not in self.__states:
  100. self.__states.append(state)
  101.  
  102. def change_state(self, state):
  103. if state is None:
  104. return False
  105. if self.__cur_state is None:
  106. print("初始化为: {}".format(state.get_name()))
  107. else:
  108. print("由 {} 变为 {}".format(self.__cur_state.get_name(), state.get_name()))
  109. self.__cur_state = state
  110. self.add_state(state)
  111. return True
  112.  
  113. def get_state(self):
  114. return self.__cur_state
  115.  
  116. def _set_state_info(self, state_info):
  117. self.__state_info = state_info
  118. for state in self.__states:
  119. if state.is_match(state_info):
  120. self.change_state(state)
  121.  
  122. def _get_state_info(self):
  123. return self.__state_info
  124.  
  125. class State:
  126. def __init__(self, name):
  127. self.__name = name
  128.  
  129. def get_name(self):
  130. return self.__name
  131.  
  132. def is_match(self, state_info):
  133. return False
  134.  
  135. @abstractmethod
  136. def behavior(self, context):
  137. pass
  138.  
  139. class Water(Context):
  140.  
  141. def __init__(self):
  142. super().__init__()
  143. self.add_state(SolidState("固态"))
  144. self.add_state(LiquidState("液态"))
  145. self.add_state(GaseousState("气态"))
  146. self.set_temperature(25)
  147.  
  148. def get_temperature(self):
  149. return self._get_state_info()
  150.  
  151. def set_temperature(self, temperature):
  152. self._set_state_info(temperature)
  153.  
  154. def rise_temperature(self, step):
  155. self.set_temperature(self.get_temperature() + step)
  156.  
  157. def reduce_temperature(self, step):
  158. self.set_temperature(self.get_temperature() - step)
  159.  
  160. def behavior(self):
  161. state = self.get_state()
  162. if isinstance(state, State):
  163. state.behavior(self)
  164.  
  165. def singleton(cls, *args, **kwargs):
  166. instance = {}
  167.  
  168. def __singletone(*args, **kwargs):
  169. if cls not in instance:
  170. instance[cls] = cls(*args, **kwargs)
  171. return instance[cls]
  172.  
  173. return __singletone
  174.  
  175. @singleton
  176. class SolidState(State):
  177. def __init__(self, name):
  178. super().__init__(name)
  179.  
  180. def is_match(self, state_info):
  181. return state_info < 0
  182.  
  183. def behavior(self, context):
  184. print(", 我性格高冷, 当前体温: {}".format(context._get_state_info()))
  185.  
  186. @singleton
  187. class LiquidState(State):
  188. def __init__(self, name):
  189. super().__init__(name)
  190.  
  191. def is_match(self, state_info):
  192. return 0 <= state_info < 100
  193.  
  194. def behavior(self, context):
  195. print("我性格温和, 当前体温: {}".format(context._get_state_info()))
  196.  
  197. @singleton
  198. class GaseousState(State):
  199. def __init__(self, name):
  200. super().__init__(name)
  201.  
  202. def is_match(self, state_info):
  203. return state_info >= 100
  204.  
  205. def behavior(self, context):
  206. print("我性格热烈,当前体温: {}".format(context._get_state_info()))
  207.  
  208. def test_state():
  209. water = Water()
  210. water.behavior()
  211. water.set_temperature(-4)
  212. water.behavior()
  213. water.rise_temperature(18)
  214. water.behavior()
  215. water.rise_temperature(110)
  216. water.behavior()
  217.  
  218. test_state()
  1. C:\Python36\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
  2. 初始化为: 液态
  3. 我性格温和, 当前体温:
  4. 液态 变为 固态
  5. 我性格高冷, 当前体温: -
  6. 固态 变为 液态
  7. 我性格温和, 当前体温:
  8. 液态 变为 气态
  9. 我性格热烈,当前体温:
  10.  
  11. Process finished with exit code

<人人都懂设计模式>-状态模式的更多相关文章

  1. <人人都懂设计模式>-中介模式

    真正的用房屋中介来作例子, 好的书籍总是让人记忆深刻. class HouseInfo: def __init__(self, area, price, has_window, has_bathroo ...

  2. <人人都懂设计模式>-单例模式

    这个模式,我还是了解的. 书上用了三种不同的方法. class Singleton1: # 单例实现方式1 __instance = None __is_first_init = False def ...

  3. <人人都懂设计模式>-装饰模式

    书上,真的用一个人穿衣打拌来讲解装饰模式的呢. from abc import ABCMeta, abstractmethod class Person(metaclass=ABCMeta): def ...

  4. 14. 星际争霸之php设计模式--状态模式

    题记==============================================================================本php设计模式专辑来源于博客(jymo ...

  5. 人人都懂区块链--pdf电子版学习资料下载

    人人都懂区块链 21天从区块链“小白”到资深玩家电子版pdf下载 链接:https://pan.baidu.com/s/1TWxYv4TLa2UtTgU-HqLECQ 提取码:6gy0 好的学习资料需 ...

  6. [Head First设计模式]生活中学设计模式——状态模式

    系列文章 [Head First设计模式]山西面馆中的设计模式——装饰者模式 [Head First设计模式]山西面馆中的设计模式——观察者模式 [Head First设计模式]山西面馆中的设计模式— ...

  7. 深入浅出设计模式——状态模式(State Pattern)

    模式动机 在很多情况下,一个对象的行为取决于一个或多个动态变化的属性,这样的属性叫做状态,这样的对象叫做有状态的 (stateful)对象,这样的对象状态是从事先定义好的一系列值中取出的.当一个这样的 ...

  8. 24种设计模式--状态模式【State Pattern】

    现在城市发展很快,百万级人口的城市一堆一堆的,那其中有两个东西的发明在城市的发展中起到非常重要的作用:一个是汽车,一个呢是...,猜猜看,是什么?是电梯!汽车让城市可以横向扩展,电梯让城市可以纵向延伸 ...

  9. C++设计模式——状态模式

    前言 在实际开发中,我们经常会遇到这种情况:一个对象有多种状态,在每一个状态下,都会有不同的行为.那么在代码中我们经常是这样实现的. typedef enum tagState { state, st ...

随机推荐

  1. IntelliJ idea 创建Web项目后web文件夹下没有WEB-INF的解决方法

    1.Ctrl+Shift+Alt+S快捷键进入Project structure(项目结构)管理的界面 2.选择左边菜单栏里的Facet,点击后能看到有Deployment Descriptors的输 ...

  2. Python--单元四练习

    一.算24 描述: 给出4个小于10的正整数,可以使用加.减.乘.除4种运算以及括号把4个数连接起来得到一个表达式.现在问题是,是否存在一种方式使得所得表达式的结果等于24.‪‬‪‬‪‬‪‬‪‬‮‬‪ ...

  3. [LeetCode] 210. Course Schedule II 课程清单之二

    There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prereq ...

  4. [LeetCode] 112. Path Sum 二叉树的路径和

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  5. django实战(五)--增加数据

    urls.py urlpatterns=[ path('curd/add/',views.curd_add,name='curdadd'), path('curd/saveadd/',views.cu ...

  6. 使用Django REST框架创建一个简单的Api

    Create a Simple API Using Django REST Framework in Python WHAT IS AN API API stands for application ...

  7. SpringBoot 系列教程自动配置选择生效

    191214-SpringBoot 系列教程自动配置选择生效 写了这么久的 Spring 系列博文,发现了一个问题,之前所有的文章都是围绕的让一个东西生效:那么有没有反其道而行之的呢? 我们知道可以通 ...

  8. vue需求表单有单位(时分秒千克等等)

    需求如下: 问题分析: 因为用elementui组件 el-input 相当于块级元素,后面的单位<span>分</span>会被挤下去,无法在同一水平. 解决方法: 不用它的 ...

  9. SQL-----数据库三种删除方式详解

    第一种  使用delete  语句 特点: delete 属于数据库操纵语言DML,表示删除表中的数据, 删除过程是每次从表中删除一行,并把该行删除操作作为事务记录在日志中保存 可以配合事件(tran ...

  10. 网络基础-------------给电脑设置IP

    ip 是每一台电脑进入互联网的一个必备钥匙,没有它就不能体会冲浪的乐趣,当我们使用电脑连接无线时我们就会被自动分配一个ip地址(DHCP),这样我们就可以凭借这个IPV4地址来进行冲浪了,但是自动分配 ...