python原型模式和單例模式學習

2021-10-07 11:08:15 字數 3456 閱讀 2788

**實現

import copy

class website:

def __init__(self, name, domain, description, author, **kwargs):

'''examples of optional attributes (kwargs):

category, creation_date, technologies, keywords.

'''

self.name = name

self.domain = domain

self.description = description

self.author = author

for key in kwargs:

setattr(self, key, kwargs[key])

def __str__(self):

summary = [f'website ""\n',]

infos = vars(self).items()

ordered_infos = sorted(infos)

for attr, val in ordered_infos:

if attr == 'name':

continue

return ''.join(summary)

class prototype:

def __init__(self):

self.objects = dict()

def register(self, identifier, obj):

self.objects[identifier] = obj

def unregister(self, identifier):

del self.objects[identifier]

def clone(self, identifier, **attrs):

found = self.objects.get(identifier)

if not found:

raise valueerror(f'incorrect object identifier: ')

obj = copy.deepcopy(found)

for key in attrs:

setattr(obj, key, attrs[key])

return obj

def main():

keywords = ('python', 'data', 'apis', 'automation')

site1 = website('contentgardening',

domain='contentgardening.com',

author='kamon ayeva',

category='blog',

keywords=keywords)

prototype = prototype()

identifier = 'ka-cg-1'

prototype.register(identifier, site1)

site2 = prototype.clone(identifier,

name='contentgardeningplayground',

domain='play.contentgardening.com',

description='experimentation for techniques featured on the blog',

category='membership site',

creation_date='2018-08-01')

for site in (site1, site2):

print(site)

print(f'id site1 : != id site2 : ')

if __name__ == '__main__':

main()

首先,匯入copy模組

定義website類,並新增前文所示的初始化方法(__init__())和字串展示方法(__str__()

定義prototype類

新增main函式

實現

首先為單例模式實現乙個元類,其中元類的__call()__方法確保只能建立乙個類例項

繼承元類

**實現

import urllib.parse

import urllib.request

class singletontype(type):

_instances = {}

def __call__(cls, *args, **kwargs):

if cls not in cls._instances:

cls._instances[cls] = super(singletontype, cls).__call__(*args, **kwargs)

return cls._instances[cls]

class urlfetcher(metaclass=singletontype):

def __init__(self):

self.urls =

def fetch(self, url):

req = urllib.request.request(url)

with urllib.request.urlopen(req) as response:

if response.code == 200:

the_page = response.read()

print(the_page)

urls = self.urls

self.urls = urls

def dump_url_registry(self):

return ', '.join(self.urls)

def main():

my_urls = ['',

'',

'','',

]print(urlfetcher() is urlfetcher())

fetcher = urlfetcher()

for url in my_urls:

try:

fetcher.fetch(url)

except exception as e:

print(e)

print('-------')

done_urls = fetcher.dump_url_registry()

print(f'done urls: ')

if __name__ == '__main__':

main()

單例模式,原型模式,享元模式

這三個模式為什麼放一起呢。都是減少建構函式多次被構造為目的產生的模式。也就是說 a a new a a b new a 這樣就兩次構造了這個物件 單例模式 在它的核心結構中只包含乙個被稱為單例的特殊類。通過單例模式可以保證系統中乙個類只有乙個例項。即乙個類只有乙個物件例項 有乙個廚師 class c...

理解設計模式之單例模式和原型模式

單例模式 就是乙個能保證在整個程序中只有乙個例項的類 一.想實現單例模式首先就不能把建構函式公開 私有化建構函式 1.私有化建構函式 private singleton 二.那如何例項化呢?提供乙個公開的靜態方法。2.公開的靜態方法提供例項 public static singleton creat...

單例和原型模式 建立型

確保乙個特殊類的例項是獨一無二的 它是這個類的唯一例項 並且這個例項易於被訪問。解決方案 1 全域性變數 乙個全域性變數使得乙個物件可以被訪問,但它不能防止你例項化多個物件。因為你的任何 都能修改全域性變數,這將不可避免的引起更多除錯的意外。換句話說,全域性變數的狀態總是會出現一些問題的。2 類建構...