【编程思想】【设计模式】【创建模式creational】原形模式Prototype
2024-09-08 18:33:05
Python版
https://github.com/faif/python-patterns/blob/master/creational/prototype.py
#!/usr/bin/env python
# -*- coding: utf-8 -*- """
*TL;DR80
Creates new object instances by cloning prototype.
""" class Prototype(object): value = 'default' def clone(self, **attrs):
"""Clone a prototype and update inner attributes dictionary"""
# Python in Practice, Mark Summerfield
obj = self.__class__()
obj.__dict__.update(attrs)
return obj class PrototypeDispatcher(object): def __init__(self):
self._objects = {} def get_objects(self):
"""Get all objects"""
return self._objects def register_object(self, name, obj):
"""Register an object"""
self._objects[name] = obj def unregister_object(self, name):
"""Unregister an object"""
del self._objects[name] def main():
dispatcher = PrototypeDispatcher()
prototype = Prototype() d = prototype.clone()
a = prototype.clone(value='a-value', category='a')
b = prototype.clone(value='b-value', is_checked=True)
dispatcher.register_object('objecta', a)
dispatcher.register_object('objectb', b)
dispatcher.register_object('default', d)
print([{n: p.value} for n, p in dispatcher.get_objects().items()]) if __name__ == '__main__':
main() ### OUTPUT ###
# [{'objectb': 'b-value'}, {'default': 'default'}, {'objecta': 'a-value'}]
Python转载版
最新文章
- [LeetCode] House Robber II 打家劫舍之二
- Mysql5.0没有nvarchar,national
- H5开发中的问题总结
- 用HttpSessionListener与HttpSessionBindingListener实现在线人数统计
- CentOS上的RabbitMQ安装
- qwt总结1
- cocos2d-x核心基础类
- [转]jQuery EasyUI 扩展-- 主题(Themes)
- 2013年全球IT公司市值排行榜
- oracle常用命令收集
- Axios Token验证拦截器
- Linux基础入门-目录结构及文件基本操作
- 正则表达式(_ % regexp_like)
- .NET Core 2.0 httpclient 请求卡顿解决方法
- Ubuntu关闭(重启)网络服务命令
- 2d场景背景无限滚动
- T-SQL行合并成列与列拆分成行
- Git从零开始(一)
- 如何提高单片机Flash的擦写次数
- tensorflow-base_operations
热门文章
- SpringBoot 居然有 44 种应用启动器
- Failed to start connector [Connector[HTTP/1.1-8080]]
- 12组-Alpha冲刺-4/6
- 浏览器调用接口正常,jmeter调不通的可能原因
- dos的基本命令
- [luogu7340]Balance
- [bzoj3038]上帝造题的7分钟2
- ML2021 | (腾讯)PatrickStar:通过基于块的内存管理实现预训练模型的并行训练
- springboot增加多端口管理
- watch异步操作