實現
定義抽象介面,維護乙個實現者(需要為幫助獲取內容的實現類定義介面)的物件引用
為獲取內容的實現類定義介面:python使用元類和抽象基類(abc)定義等價的介面
實現實現者介面並定義其具體實現
主函式呼叫:
**實現
import abc
import urllib.parse
import urllib.request
class resourcecontent:
"""define the abstraction's inte***ce.
maintain a reference to an object which represents the implementor.
"""def __init__(self, imp):
self._imp = imp
def show_content(self, path):
self._imp.fetch(path)
class resourcecontentfetcher(metaclass=abc.abcmeta):
"""define the inte***ce (implementor) for implementation classes that help fetch content.
"""@abc.abstractmethod
def fetch(path):
pass
class urlfetcher(resourcecontentfetcher):
"""implement the implementor inte***ce and define its concrete
implementation.
"""def fetch(self, path):
# path is an url
req = urllib.request.request(path)
with urllib.request.urlopen(req) as response:
if response.code == 200:
the_page = response.read()
print(the_page)
class localfilefetcher(resourcecontentfetcher):
"""implement the implementor inte***ce and define its concrete
implementation.
"""def fetch(self, path):
# path is the filepath to a text file
with open(path) as f:
print(f.read())
def main():
url_fetcher = urlfetcher()
iface = resourcecontent(url_fetcher)
iface.show_content('')
print('***************====')
localfs_fetcher = localfilefetcher()
iface = resourcecontent(localfs_fetcher)
iface.show_content('file.txt')
if __name__ == "__main__":
main()
Python設計模式 四 橋接模式
橋接模式 具體實現者1 2 class drawingapi1 object defdraw circle self,x,y,radius print api1.circle at 半徑 format x,y,radius 具體實現者2 2 class drawingapi2 object defd...
Python設計模式之橋接模式
橋接模式學習鏈結 usr bin python coding utf8 橋接模式 具體實現者1 2 class drawingapi1 object def draw circle self,x,y,radius print api1.circle at 半徑 format x,y,radius 具...
學習設計模式(4) 橋接模式
今天學習了橋接模式,感覺很受啟發。1.橋接模式uml圖 2.理解橋接模式 1 將抽象和實現分離開來。2 不同的實現可以自由發展。3 不同的抽象,也可以有許多不同的繼承,這些繼承可以多種多樣。3.說明 1 shape是最高抽象,然後你可以自己繼承多種形狀,圓形,方形,星型,三角形等等。而且就方形而言,...