我在設計我的軟體時遇到了一個問題。
我的軟體包含幾個類Bot、Website、 和Scraper。
Bot 是最抽象的執行類,負責在高層管理程式。
Website 是一個包含從該特定網站抓取的資料的類。
Scraper是一個類,每個Website. 每個實體負責單個網站的不同部分。
Scraper有一個函式scrape_data()回傳與Website. 我想以Website某種方式將這些資料傳遞給,但找不到方法,因為Scraper它處于較低的抽象級別。這是我嘗試過的想法:
# In this idea, Website would have to poll scraper. Scraper is already polling Server, so this seems messy and inefficient
class Website:
def __init__(self):
self.scrapers = list()
self.data = dict()
def add_scraper(self, scraper):
self.scrapers.append(scraper)
def add_data(type, json):
self.data[type] = json
...
# The problem here is scraper has no awareness of the dict of websites. It cannot pass the data returned by Scraper into the respective Website
class Bot:
def __init__(self):
self.scrapers = list()
self.websites = dict()
我該如何解決我的問題?什么樣的更基本的規則或設計模式適用于這個問題,以便我將來可以使用它們?
uj5u.com熱心網友回復:
解決這個問題的一種方法是,從節點結構中汲取靈感,在Scraper類中有一個屬性直接參考其各自的Website,就好像我正確理解您描述的一對多關系(一個Website可以有多個Scrapers)。然后,當 aScraper需要將其資料傳遞給它時Website,您可以直接參考該屬性:
class Website:
def __init__(self):
self.scrapers = list() #You can indeed remove this list of scrapers since the
#scrapper will reference its master website, not the other way around
self.data = dict() #I'm not sure how you want the data to be stores,
#it could be a list, a dict, etc.
def add_scraper(self, scraper):
self.scrapers.append(scraper)
def add_data(type, json):
self.data[type] = json
class Scraper:
def __init__(self, master_website):
#Respective code
self.master = master_website #This way you have a direct reference to the website.
#This master_website is a Website object
...
def scrape_data(self):
json = #this returns the scraped data in JSON format
self.master.add_data(type, json)
我不知道這會有多有效,或者您是否想隨時知道哪些抓取工具鏈接到哪個網站
uj5u.com熱心網友回復:
一旦您開始談論多對多的父/子關系,您就應該考慮組合模式而不是傳統的繼承。具體來說,裝飾者模式。您的add_scraper方法是一種提示,您實際上是在尋找構建處理程式堆疊。
此模式的經典示例是一組負責生成咖啡價格的類。您從一個基本成分“咖啡”開始,每種成分都有一個類,每個類都有自己的價格修飾符。一個類用于全脂牛奶,一個用于脫脂,一個用于糖,一個用于榛子糖漿,一個用于巧克力等。所有成分以及基礎組件共享一個介面,保證存在“getPrice”方法。當用戶下訂單時,基礎組件被注入到第一個成分/包裝類中。被包裝的物件被注入后續的成分包裝器等等,直到 finallygetPrice被呼叫。并且每個實體都getPrice應該被寫入,首先從之前注入的實體中提取,這樣計算就可以貫穿所有層。
好處是可以在不影響現有選單的情況下添加新成分,現有的可以單獨更改價格,并且可以將成分添加到多種型別的飲料中。
在您的情況下,被裝飾的資料結構是Website物件。成分類將是您的Scrapers,getPrice方法將是scrape_data. 并且該scrape_data方法應該期望接收一個實體Website作為引數,并在水合后回傳它。每個 Scraper 都不需要知道其他刮刀是如何作業的,或者要實施哪些刮刀。它只需要知道前一個存在并遵守一個介面,保證它也有一個scrape_data方法。并且所有人最終都將操縱同一個Website物件,因此被吐回給你的東西Bot已經被所有人吸收了。
這使您有責任知道將哪些 Scraper 應用到Website您的Bot類中,現在該類本質上是一個服務類。由于它位于上層抽象層,因此它具有了解這一點所需的高級視角。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/395605.html
上一篇:在這種情況下不使用“受保護”的任何理由(cpp、c 、oop)
下一篇:從同一個父類的另一個類訪問物件
