Introduction
Today I worked a little on Mediator Pattern. This pattern is adopted to reduce communication complexity between multiple objects. Instead of implementing inside each class the direct communication with other classes (strong coupling), a mediator object is implemented and each class can call this mediator object to communicate with others. This can bring loose coupling between classes and make it easier to develop and extend the program.
Mediator pattern is classified as abehavioral pattern.
Real life example
Currently I started using a very great applicationToo Good To Go in my daily life. This application connects customers to restaurants and stores that have unsold, surplus food. Its objective is to reduce food waste and protect our earth. I can buy "food baskets" of nearby stores on this app with a very low price. What a great idea!
See, I have reserved a basket for this evening:
This app is in fact a very good example forMediator pattern. Let's see how clients should do to query and buy available food baskets in shops without using this app (without mediator):
Now by using thisToo Good To Go app, clients now can query and buy available food baskets in this way:
Exercise in Python
Thus I would like to simulate the idea ofToo Good To Go in my exercise. Go.
Define aBasketInfo class:
## Basket of Too good to goclassBasketInfo:"""Food Basket info"""def__init__(self,location,price,address,Shop):self.__location=locationself.__price=priceself.__address=addressself.__Shop=ShopdefgetLocation(self):returnself.__locationdefgetAddress(self):returnself.__addressdefgetShopName(self):returnself.__Shop.getName()defshowInfo(self,isShowShop=True):print(" ++ Location: {}".format(self.__location))print(" ++ Price: {}".format(str(self.__price)+" euros"))print(" ++ Address: {}".format(self.__address))print(" ++ Shop:"+self.getShopName()ifisShowShopelse"")print()
TheBasketPlatformApp class which serves as Mediator:
importdifflib## Check the similarity of two stringsdefget_equal_rate(str1,str2):returndifflib.SequenceMatcher(None,str1,str2).quick_ratio()classBasketPlatformApp:"""Too Good To Go platform"""def__init__(self,name):self.__BasketInfos=[]self.__name=namedefgetName(self):returnself.__namedefaddBasketInfo(self,BasketInfo):self.__BasketInfos.append(BasketInfo)defremoveBasketInfo(self,BasketInfo):forinfoinself.__BasketInfos:if(info==BasketInfo):self.__BasketInfos.remove(info)defgetSearchCondition(self,description):returndescriptiondefgetMatchInfos(self,searchCondition):print(self.getName()," shows suitable baskets for you:")suitables=[]forinfoinself.__BasketInfos:ifget_equal_rate(searchCondition,info.getLocation())>0.9:info.showInfo(False)suitables.append(info)returnsuitablesdefaddBasket(self,BasketInfo):print(self.getName()," has a new avaible Basket\n -- Provided by",BasketInfo.getShopName(),",\n -- Located at:",BasketInfo.getAddress())defaddBaskets(self):forinfoinself.__BasketInfos:self.addBasket(info)
Now define BasketShop and Customer classes. They will not communicate directly with each other. Their communication shall be done via a mediator. Note that they do not implement each other in their code:
classBasketShop:""" BasketShop class"""def__init__(self,name):self.__name=nameself.__BasketInfo=NonedefgetName(self):returnself.__namedefsetBasketInfo(self,address,location,price):self.__BasketInfo=BasketInfo(location,price,address,self)defpublishBasketInfo(self,App):App.addBasketInfo(self.__BasketInfo)print(self.getName()+" pushes a Basket on",App.getName(),":")self.__BasketInfo.showInfo()classCustomer:"""User of TooGoodToGO"""def__init__(self,name):self.__name=namedefgetName(self):returnself.__namedeffindBasket(self,description,App):print("User"+self.getName()+", searching a backet with info:"+description)print()returnApp.getMatchInfos(App.getSearchCondition(description))defviewBasket(self,BasketInfos):size=len(BasketInfos)returnBasketInfos[size-1]defbuyBasket(self,BasketInfo,App):""" command Basket on App"""print(self.getName()," made a new command on",App.getName()," for a basket in",BasketInfo.getShopName())
Now launch a simulation ofMediator pattern:
if__name__=="__main__":myAPP=BasketPlatformApp("Too Good To Go")Paul=BasketShop("Paul");Paul.setBasketInfo("La Defense Parvis 15, 92000, Haut-Seine","4 temps commercial center",3.99)Paul.publishBasketInfo(myAPP)Auchan=BasketShop("Auchan")Auchan.setBasketInfo("22 Rue Alma, 92240, Courbevoie","Supermarcket A2Pas",4.0)Auchan.publishBasketInfo(myAPP)Sushi=BasketShop("Sushi Shop")Sushi.setBasketInfo("La Defense Parvis 15, 92000, Haut-Seine","4 temps commercial center",6.99)Sushi.publishBasketInfo(myAPP)print()myAPP.addBaskets()print()jemaloQ=Customer("jemaloQ")BasketInfos=jemaloQ.findBasket("4 temps commercial center",myAPP)print()print("Searching available baskets for you ……")print()AppropriateBasket=jemaloQ.viewBasket(BasketInfos)jemaloQ.buyBasket(AppropriateBasket,myAPP)
Execution output;
Food shops pushes available basket to APP platform:
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse