<人人都懂设计模式>-状态模式
同样是水,固态,气态,液态的变化,是由温度引起。
引此为思考状态模式。
- from abc import ABCMeta, abstractmethod
- # 引入ABCMeta和abstractmethod来定义抽象类和抽象方法
- """
- version 1.0
- class Water:
- def __init__(self, state):
- self.__temperature = 25
- self.__state = state
- def set_state(self, state):
- self.__state = state
- def change_state(self, state):
- if self.__state:
- print("由 {} 变为 {}".format(self.__state.get_name(), state.get_name()))
- else:
- print("初始化为{}".format(state.get_name()))
- self.__state = state
- def get_temperature(self):
- return self.__temperature
- def set_temperature(self, temperature):
- self.__temperature = temperature
- if self.__temperature <= 0:
- self.change_state(SolidState("固态"))
- elif self.__temperature <= 100:
- self.change_state(LiquidState("液态"))
- else:
- self.change_state(GaseousState("气态"))
- def rise_temperature(self, step):
- self.set_temperature(self.__temperature + step)
- def reduce_temperature(self, step):
- self.set_temperature(self.__temperature - step)
- def behavior(self):
- self.__state.behavior(self)
- class State:
- def __init__(self, name):
- self.__name = name
- def get_name(self):
- return self.__name
- @abstractmethod
- def behavior(self, water):
- pass
- class SolidState(State):
- def __init__(self, name):
- super().__init__(name)
- def behavior(self, water):
- print("当前体温: {}".format(str(water.get_temperature())))
- class LiquidState(State):
- def __init__(self, name):
- super().__init__(name)
- def behavior(self, water):
- print("当前体温: {}".format(str(water.get_temperature())))
- class GaseousState(State):
- def __init__(self, name):
- super().__init__(name)
- def behavior(self, water):
- print("当前体温: {}".format(str(water.get_temperature())))
- def test_state():
- water = Water(LiquidState("液态"))
- water.behavior()
- water.set_temperature(-4)
- water.behavior()
- water.rise_temperature(18)
- water.behavior()
- water.rise_temperature(110)
- water.behavior()
- test_state()
- """
- # version 2.0
- class Context(metaclass=ABCMeta):
- def __init__(self):
- self.__states = []
- self.__cur_state = None
- self.__state_info = 0
- def add_state(self, state):
- if state not in self.__states:
- self.__states.append(state)
- def change_state(self, state):
- if state is None:
- return False
- if self.__cur_state is None:
- print("初始化为: {}".format(state.get_name()))
- else:
- print("由 {} 变为 {}".format(self.__cur_state.get_name(), state.get_name()))
- self.__cur_state = state
- self.add_state(state)
- return True
- def get_state(self):
- return self.__cur_state
- def _set_state_info(self, state_info):
- self.__state_info = state_info
- for state in self.__states:
- if state.is_match(state_info):
- self.change_state(state)
- def _get_state_info(self):
- return self.__state_info
- class State:
- def __init__(self, name):
- self.__name = name
- def get_name(self):
- return self.__name
- def is_match(self, state_info):
- return False
- @abstractmethod
- def behavior(self, context):
- pass
- class Water(Context):
- def __init__(self):
- super().__init__()
- self.add_state(SolidState("固态"))
- self.add_state(LiquidState("液态"))
- self.add_state(GaseousState("气态"))
- self.set_temperature(25)
- def get_temperature(self):
- return self._get_state_info()
- def set_temperature(self, temperature):
- self._set_state_info(temperature)
- def rise_temperature(self, step):
- self.set_temperature(self.get_temperature() + step)
- def reduce_temperature(self, step):
- self.set_temperature(self.get_temperature() - step)
- def behavior(self):
- state = self.get_state()
- if isinstance(state, State):
- state.behavior(self)
- def singleton(cls, *args, **kwargs):
- instance = {}
- def __singletone(*args, **kwargs):
- if cls not in instance:
- instance[cls] = cls(*args, **kwargs)
- return instance[cls]
- return __singletone
- @singleton
- class SolidState(State):
- def __init__(self, name):
- super().__init__(name)
- def is_match(self, state_info):
- return state_info < 0
- def behavior(self, context):
- print(", 我性格高冷, 当前体温: {}".format(context._get_state_info()))
- @singleton
- class LiquidState(State):
- def __init__(self, name):
- super().__init__(name)
- def is_match(self, state_info):
- return 0 <= state_info < 100
- def behavior(self, context):
- print("我性格温和, 当前体温: {}".format(context._get_state_info()))
- @singleton
- class GaseousState(State):
- def __init__(self, name):
- super().__init__(name)
- def is_match(self, state_info):
- return state_info >= 100
- def behavior(self, context):
- print("我性格热烈,当前体温: {}".format(context._get_state_info()))
- def test_state():
- water = Water()
- water.behavior()
- water.set_temperature(-4)
- water.behavior()
- water.rise_temperature(18)
- water.behavior()
- water.rise_temperature(110)
- water.behavior()
- test_state()
- C:\Python36\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
- 初始化为: 液态
- 我性格温和, 当前体温:
- 由 液态 变为 固态
- , 我性格高冷, 当前体温: -
- 由 固态 变为 液态
- 我性格温和, 当前体温:
- 由 液态 变为 气态
- 我性格热烈,当前体温:
- Process finished with exit code
<人人都懂设计模式>-状态模式的更多相关文章
- <人人都懂设计模式>-中介模式
真正的用房屋中介来作例子, 好的书籍总是让人记忆深刻. class HouseInfo: def __init__(self, area, price, has_window, has_bathroo ...
- <人人都懂设计模式>-单例模式
这个模式,我还是了解的. 书上用了三种不同的方法. class Singleton1: # 单例实现方式1 __instance = None __is_first_init = False def ...
- <人人都懂设计模式>-装饰模式
书上,真的用一个人穿衣打拌来讲解装饰模式的呢. from abc import ABCMeta, abstractmethod class Person(metaclass=ABCMeta): def ...
- 14. 星际争霸之php设计模式--状态模式
题记==============================================================================本php设计模式专辑来源于博客(jymo ...
- 人人都懂区块链--pdf电子版学习资料下载
人人都懂区块链 21天从区块链“小白”到资深玩家电子版pdf下载 链接:https://pan.baidu.com/s/1TWxYv4TLa2UtTgU-HqLECQ 提取码:6gy0 好的学习资料需 ...
- [Head First设计模式]生活中学设计模式——状态模式
系列文章 [Head First设计模式]山西面馆中的设计模式——装饰者模式 [Head First设计模式]山西面馆中的设计模式——观察者模式 [Head First设计模式]山西面馆中的设计模式— ...
- 深入浅出设计模式——状态模式(State Pattern)
模式动机 在很多情况下,一个对象的行为取决于一个或多个动态变化的属性,这样的属性叫做状态,这样的对象叫做有状态的 (stateful)对象,这样的对象状态是从事先定义好的一系列值中取出的.当一个这样的 ...
- 24种设计模式--状态模式【State Pattern】
现在城市发展很快,百万级人口的城市一堆一堆的,那其中有两个东西的发明在城市的发展中起到非常重要的作用:一个是汽车,一个呢是...,猜猜看,是什么?是电梯!汽车让城市可以横向扩展,电梯让城市可以纵向延伸 ...
- C++设计模式——状态模式
前言 在实际开发中,我们经常会遇到这种情况:一个对象有多种状态,在每一个状态下,都会有不同的行为.那么在代码中我们经常是这样实现的. typedef enum tagState { state, st ...
随机推荐
- IntelliJ idea 创建Web项目后web文件夹下没有WEB-INF的解决方法
1.Ctrl+Shift+Alt+S快捷键进入Project structure(项目结构)管理的界面 2.选择左边菜单栏里的Facet,点击后能看到有Deployment Descriptors的输 ...
- Python--单元四练习
一.算24 描述: 给出4个小于10的正整数,可以使用加.减.乘.除4种运算以及括号把4个数连接起来得到一个表达式.现在问题是,是否存在一种方式使得所得表达式的结果等于24. ...
- [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 ...
- [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 ...
- django实战(五)--增加数据
urls.py urlpatterns=[ path('curd/add/',views.curd_add,name='curdadd'), path('curd/saveadd/',views.cu ...
- 使用Django REST框架创建一个简单的Api
Create a Simple API Using Django REST Framework in Python WHAT IS AN API API stands for application ...
- SpringBoot 系列教程自动配置选择生效
191214-SpringBoot 系列教程自动配置选择生效 写了这么久的 Spring 系列博文,发现了一个问题,之前所有的文章都是围绕的让一个东西生效:那么有没有反其道而行之的呢? 我们知道可以通 ...
- vue需求表单有单位(时分秒千克等等)
需求如下: 问题分析: 因为用elementui组件 el-input 相当于块级元素,后面的单位<span>分</span>会被挤下去,无法在同一水平. 解决方法: 不用它的 ...
- SQL-----数据库三种删除方式详解
第一种 使用delete 语句 特点: delete 属于数据库操纵语言DML,表示删除表中的数据, 删除过程是每次从表中删除一行,并把该行删除操作作为事务记录在日志中保存 可以配合事件(tran ...
- 网络基础-------------给电脑设置IP
ip 是每一台电脑进入互联网的一个必备钥匙,没有它就不能体会冲浪的乐趣,当我们使用电脑连接无线时我们就会被自动分配一个ip地址(DHCP),这样我们就可以凭借这个IPV4地址来进行冲浪了,但是自动分配 ...