<人人都懂设计模式>-状态模式
同样是水,固态,气态,液态的变化,是由温度引起。
引此为思考状态模式。
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 ...
随机推荐
- docker--发布docker镜像
前戏 前面我们自己做了个docker镜像,我们可以上传到docker hub,别人就可以下载使用了 发布到docker hub 我们前面使用docker search 查找的镜像都是从docker h ...
- appium--Toast元素识别
前戏 Android中的Toast是一种简易的消息提示框,当视图显示给用户,在应用程序中显示为浮动,和Dialog不一样的是,它永远不会获得焦点,无法被点击 Toast类的思想就是尽可能不引人注意,同 ...
- Linux性能优化实战学习笔记:第四十一讲
一.上节回顾 上一节,我们探究了网络延迟增大问题的分析方法,并通过一个案例,掌握了如何用hping3.tcpdump.Wireshark.strace 等工具,来排查和定位问题的根源. 简单回顾一下, ...
- [LeetCode] 377. Combination Sum IV 组合之和之四
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
- [LeetCode] 204. Count Primes 质数的个数
Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 E ...
- LoadRunner名词解释
Transactions(用户事务分析):用户事务分析是站在用户角度进行的基础性能分析. 1.Transation Sunmmary(事务综述) 对事务进行综合分析是性能分析的第一步,通过分析测试时间 ...
- 消息队列:RabbitMQ安装
1. 安装RabbitMQ之前需要先安装Erlang环境 然后配置环境变量 2. 安装完后 我们进入到我们安装到 sbin目录C:\Program Files\RabbitMQ Server\rabb ...
- 关于ProxmoxVE
1) PVE简介 PVE是Proxmox Virtual Environment(Proxmox虚拟化环境,也通常简称为Proxmox VE)的简称,它是基于QEMU/KVM和LXC的开源服务器虚拟化 ...
- Python Web编程
1.统一资源定位符(URL) URL用来在Web上定位一个文档.浏览器只是Web客户端的一种,任何一个向服务器端发送请求来获取数据的应用程序都被认为是客户端 URL格式:port_sch://net_ ...
- SpringBoot第十七篇:定时任务
作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/11076555.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言 相信大家对 ...