Sometimes you have a system that becomes quite complex over time as more features are added or modified. It may be useful to provide a simplified API over it. This is the Facade pattern.
The Facade pattern essentially is an alternative, reduced or simplified interface to a set of other interfaces, abstractions and implementations within a system that may be full of complexity and/or tightly coupled.
It can also be considered as a higher-level interface that shields the consumer from the unnecessary low-level complications of integrating into many subsystems.
This is an example of a game engine API. The facade layer is creating one streamlined interface consisting of several methods from several larger API backend systems.
The client could connect directly to each subsystem's API and implement its authentication protocols, specific methods, etc. While it is possible, it would be quite a lot of consideration for each of the development teams, so the facade API unifies the common methods that becomes much less overwhelming for each new client developer to integrate into.
"The Facade Example Use Case"importtimefromdecimalimportDecimalfromgame_apiimportGameAPIUSER={"user_name":"sean"}USER_ID=GameAPI.register_user(USER)time.sleep(1)GameAPI.submit_entry(USER_ID,Decimal('5'))time.sleep(1)print()print("---- Gamestate Snapshot ----")print(GameAPI.game_state())time.sleep(1)HISTORY=GameAPI.get_history()print()print("---- Reports History ----")forrowinHISTORY:print(f"{row} : {HISTORY[row][0]} : {HISTORY[row][1]}")print()print("---- Gamestate Snapshot ----")print(GameAPI.game_state())
"The Game API facade"fromdecimalimportDecimalfromusersimportUsersfromwalletsimportWalletsfromgame_engineimportGameEnginefromreportsimportReportsclassGameAPI():"The Game API facade"@staticmethoddefget_balance(user_id:str)->Decimal:"Get a players balance"returnWallets.get_balance(user_id)@staticmethoddefgame_state()->dict:"Get the current game state"returnGameEngine().get_game_state()@staticmethoddefget_history()->dict:"get the game history"returnReports.get_history()@staticmethoddefchange_pwd(user_id:str,password:str)->bool:"change users password"returnUsers.change_pwd(user_id,password)@staticmethoddefsubmit_entry(user_id:str,entry:Decimal)->bool:"submit a bet"returnGameEngine().submit_entry(user_id,entry)@staticmethoddefregister_user(value:dict[str,str])->str:# Python 3.9# def register_user(value) -> str: # Python 3.8 and earlier"register a new user and returns the new id"returnUsers.register_user(value)
"A Singleton Dictionary of Users"fromdecimalimportDecimalfromwalletsimportWalletsfromreportsimportReportsclassUsers():"A Singleton Dictionary of Users"_users:dict[str,dict[str,str]]={}# Python 3.9# _users = {} # Python 3.8 or earlierdef__new__(cls):returncls@classmethoddefregister_user(cls,new_user:dict[str,str])->str:# Python 3.9# def register_user(cls, new_user) -> str: # Python 3.8 or earlier"register a user"ifnotnew_user["user_name"]incls._users:# generate really complicated unique user_id.# Using the existing user_name as the id for simplicityuser_id=new_user["user_name"]cls._users[user_id]=new_userReports.log_event(f"new user `{user_id}` created")# create a wallet for the new userWallets().create_wallet(user_id)# give the user a sign up bonusReports.log_event(f"Give new user `{user_id}` sign up bonus of 10")Wallets().adjust_balance(user_id,Decimal(10))returnuser_idreturn""@classmethoddefedit_user(cls,user_id:str,user:dict):"do nothing"print(user_id)print(user)returnFalse@classmethoddefchange_pwd(cls,user_id:str,password:str):"do nothing"print(user_id)print(password)returnFalse
"A Singleton Dictionary of User Wallets"fromdecimalimportDecimalfromreportsimportReportsclassWallets():"A Singleton Dictionary of User Wallets"_wallets:dict[str,Decimal]={}# Python 3.9# _wallets = {} # Python 3.8 or earlierdef__new__(cls):returncls@classmethoddefcreate_wallet(cls,user_id:str)->bool:"A method to initialize a users wallet"ifnotuser_idincls._wallets:cls._wallets[user_id]=Decimal('0')Reports.log_event(f"wallet for `{user_id}` created and set to 0")returnTruereturnFalse@classmethoddefget_balance(cls,user_id:str)->Decimal:"A method to check a users balance"Reports.log_event(f"Balance check for `{user_id}` = {cls._wallets[user_id]}")returncls._wallets[user_id]@classmethoddefadjust_balance(cls,user_id:str,amount:Decimal)->Decimal:"A method to adjust a user balance up or down"cls._wallets[user_id]=cls._wallets[user_id]+Decimal(amount)Reports.log_event(f"Balance adjustment for `{user_id}`. "f"New balance = {cls._wallets[user_id]}")returncls._wallets[user_id]
./facade/reports.py
1 2 3 4 5 6 7 8 91011121314151617181920212223
"A Singleton Dictionary of Reported Events"importtimeclassReports():"A Singleton Dictionary of Reported Events"_reports:dict[int,tuple[float,str]]={}# Python 3.9# _reports = {} # Python 3.8 or earlier_row_id=0def__new__(cls):returncls@classmethoddefget_history(cls)->dict:"A method to retrieve all historic events"returncls._reports@classmethoddeflog_event(cls,event:str)->bool:"A method to add a new event to the record"cls._reports[cls._row_id]=(time.time(),event)cls._row_id=cls._row_id+1returnTrue
"The Game Engine"importtimefromdecimalimportDecimalfromwalletsimportWalletsfromreportsimportReportsclassGameEngine():"The Game Engine"_instance=None_start_time:int=0_clock:int=0_entries:list[tuple[str,Decimal]]=[]# Python 3.9# _entries = [] # Python 3.8 or earlier_game_open=Truedef__new__(cls):ifcls._instanceisNone:cls._instance=GameEnginecls._start_time=int(time.time())cls._clock=60returncls._instance@classmethoddefget_game_state(cls)->dict:"Get a snapshot of the current game state"now=int(time.time())time_remaining=cls._start_time-now+cls._clockiftime_remaining<0:time_remaining=0cls._game_open=Falsereturn{"clock":time_remaining,"game_open":cls._game_open,"entries":cls._entries}@classmethoddefsubmit_entry(cls,user_id:str,entry:Decimal)->bool:"Submit a new entry for the user in this game"now=int(time.time())time_remaining=cls._start_time-now+cls._clockiftime_remaining>0:ifWallets.get_balance(user_id)>Decimal('1'):ifWallets.adjust_balance(user_id,Decimal('-1')):cls._entries.append((user_id,entry))Reports.log_event(f"New entry `{entry}` submitted by `{user_id}`")returnTrueReports.log_event(f"Problem adjusting balance for `{user_id}`")returnFalseReports.log_event(f"User Balance for `{user_id}` to low")returnFalseReports.log_event("Game Closed")returnFalse
In the Facade use case example, I have added type hints to the method signatures and class attributes.
_clock:int=0_entries:list[tuple[str,Decimal]]=[]...defget_balance(user_id:str)->Decimal:"Get a players balance"......defregister_user(cls,new_user:dict[str,str])->str:"register a user"...
See the extra : str after the user_id attribute, and the -> Decimal before the final colon in the get_balance() snippet.
This is indicating that if you use the get_balance() method, that the user_id should be a type of string, and that the method will return a Decimal.
Note that the Python runtime does not enforce the type hints and that they are optional. However, where they are beneficial is in the IDE of your choice or other third party tools such type checkers.
In VSCode, when typing code, it will show the types that the method needs.
For type checking, you can install an extra module called mypy
Mypy will also check any imported modules at the same time.
If working with money, then it is advisable to add extra checks to your code. Checking that type usage is consistent throughout your code, especially when using Decimals, is a good idea that will make your code more robust.
For example, if I wasn't consistent in using the Decimal throughout my code, then I would see a warning highlighted.
Use when you want to provide a simple interface to a complex subsystem.
You want to layer your subsystems into an abstraction that is easier to understand.
Abstract Factory and Facade can be considered very similar. An Abstract Factory is about creating in interface over several creational classes of similar objects, whereas the Facade is more like an API layer over many creational, structural and/or behavioral patterns.
The Mediator is similar to the Facade in the way that it abstracts existing classes. The Facade is not intended to modify, load balance or apply any extra logic. A subsystem does not need to consider that existence of the facade, it would still work without it.
A Facade is a minimal interface that could also be implemented as a Singleton.
A Facade is an optional layer that does not alter the subsystem. The subsystem does not need to know about the Facade, and could even be used by many other facades created for different audiences.