首页 > 编程语言 >Python: Flyweight Pattern

Python: Flyweight Pattern

时间:2022-10-29 19:31:16浏览次数:51  
标签:__ arr Flyweight Python Pattern self arrow velocity def





DuFlyweight.py

# 享元模式 Flyweight Pattern  geovindu,Geovin Du,涂聚文
import time

class Arrow:
def __init__(self, x, y, z, velocity):
self.x = x
self.y = y
self.z = z
self.velocity = velocity
self.shape = 'cone'


class ArrowContext:
def __init__(self, x, y, z, velocity):
self.x = x
self.y = y
self.z = z
self.velocity = velocity


class ArrowFlyweight:
def __init__(self):
self.shape = 'cone'
self.arrows = []

def arrow_factory(self, x, y, z, velocity):
arr = []
for b in self.arrows:
if b.x == x and b.y == y and b.z == z and b.velocity == velocity:
arr.append(b)
if not arr:
arr = Arrow(x, y, z, velocity)
self.arrows.append(arr)
else:
arr = arr[0]

return arr

def print_arrows(self):
print('排列:')
for arrow in self.arrows:
print(str(arrow.x) + ' ' + str(arrow.y) + ' ' + str(arrow.z) + ' ' + str(arrow.velocity))


# Flyweight Object: HTTP Request result: geovindu,Geovin Du,涂聚文 格式,排版要对齐,否则调用时,方法到提取不到
class WebRequestResult(object):
# The time (in munutes, converted to seconds) to cache a request.
# This is a 1-minute cahce.
CACHE_TIME_MINUTES = 1 * 60

def __init__(self, data):
# The Flyweight data:
self.data = data
self.cacheUntilTime = time.time() + WebRequestResult.CACHE_TIME_MINUTES

def isExpired(self):
return time.time() > self.cacheUntilTime

# WebRequestCache Factory:
class WebRequestCache(object):
def __init__(self):
self.cache = {}

# For simplicity, we'll be concurrent with our requests:
def getRequest(self, url):
result = None

if url in self.cache:
result = self.cache[url]

if result is None or result.isExpired():
result = WebRequestResult("一些数据来自于 " + str(url))

self.cache[url] = result

return result

main.py  调用

# 享元模式 Flyweight Pattern

obj =DuFlyweight.ArrowFlyweight()
obj.arrow_factory(1, 1, 1, 1)
obj.arrow_factory(1, 2, 5, 1)
obj.arrow_factory(1, 1, 1, 1)
obj.print_arrows()

geovinduObject =DuFlyweight.ArrowFlyweight()
geovinduObject.arrow_factory('geovindu', 'dusystem.com', '1', '塗聚文')
geovinduObject.arrow_factory('geovin', 'du', '5', '1')
geovinduObject.arrow_factory('geovi', 'studio', '1', '涂聚文')
geovinduObject.print_arrows()

webCache = DuFlyweight.WebRequestCache()

request = webCache.getRequest("https://coronavirus-tracker-api.herokuapp.com/all")
print(request.data) # output: Some cool data from mycoolapi/endpoint

print(request.isExpired()) # output: False

输出:

排列:
1 1 1 1
1 2 5 1
排列:
geovindu dusystem.com 1 塗聚文
geovin du 5 1
geovi studio 1 涂聚文
一些数据来自于 https://coronavirus-tracker-api.herokuapp.com/all
False

标签:__,arr,Flyweight,Python,Pattern,self,arrow,velocity,def
From: https://blog.51cto.com/geovin/5806483

相关文章