id
int64
0
25.6k
text
stringlengths
0
4.59k
8,100
interpreter pattern the composite pattern defines both composite ( non-terminalsclasses and leaf ( terminalsclasses that can be used to construct composite componentsuch as special rule class leaf(object)def __init__(self*args**kwargs)pass def component_function(self)print("leaf"class composite(object)def __init__(self...
8,101
interpreter pattern def calculate_cost(self)return sum( cost for in self itemsdef calculate_discount(self)return sum( for in self discountsclass item(object)def __init__(selfnameitem_typecost)self name name self item_type item_type self cost cost class itemtype(object)def __init__(selfname)self name name class customer...
8,102
interpreter pattern def add_percentage_discount(selfitem_typepercent)if item_type ="any item" lambda xtrue elsef lambda xx item_type =item_type items_to_discount [item for item in self tab items if (item)for item in items_to_discountdiscount discount(item cost (percent/ )self discounts append(discountdef apply(self)if ...
8,103
interpreter pattern print"calculated cost{}\ndiscount applied{}\ {}discount appliedformattab calculate_cost()tab calculate_discount() tab calculate_discount(tab calculate_cost(now that we have single rule workingusing objects that result in some form of readable codelet' return to the implementation of the dsl using t...
8,104
interpreter pattern class condition(object)def __init__(selfcondition_function)self test condition_function def evaluate(selftab)return self test(tabclass discounts(object)def __init__(self)self children [def calculate(selftab)return sum( calculate(tabfor in self childrendef add(selfchild)self children append(childdef ...
8,105
interpreter pattern def apply(self)if self conditions evaluate(self tab)return self discounts calculate(self tabreturn implementing the interpreter pattern two types of people use softwarethose who are satisfied with the offering out of the box and those who are willing to tinker and tweak to make the software fit the...
8,106
interpreter pattern finallythe interpreter pattern can be used to decide if certain tab qualifies for any specials firstthe tab and item classes are definedfollowed by the classes needed for the grammar thensome sentences in the grammar are implemented and tested using test tabs note that we hard code the types in this...
8,107
interpreter pattern def evaluate(selftab)return self expression evaluate(tabor self expression evaluate(tabclass percentagediscount(object)def __init__(selfitem_typepercentage)self item_type item_type self percentage percentage def calculate(selftab)return (sum([ cost for in tab items if item_type =self item_type]sel...
8,108
interpreter pattern from_hourfrom_minute [int(xfor in self from_time split(":")to_hourto_minute [int(xfor in self to_time split(":")hour_in_range from_hour <hour_now to_hour begin_edge hour_now =from_hour and minute_now from_minute end_edge hour_now =to_hour and minute_now to_minute return any(hour_in_rangebegin_edgee...
8,109
interpreter pattern class itemisa(object)def __init__(selfitem_type)self item_type item_type def evaluate(selfitem)return self item_type =item item_type class numberofitemsoftype(object)def __init__(selfnumber_of_itemsitem_type)self number number_of_items self item_type item_type def evaluate(selftab)return len([ for ...
8,110
interpreter pattern class itemtype(object)def __init__(selfname)self name name class customer(object)def __init__(selfcustomer_typename)self customer_type customer_type self name name class customertype(object)def __init__(selfcustomer_type)self customer_type customer_type member customertype("member"pizza itemtype("pi...
8,111
interpreter pattern rulecustomerisa(member)percentagediscount("any_item" during happy hourwhich happens from : to : weekdaysall drinks are less rules appendruleand(timeisbetween(" : "" : ")todayisaweekday())percentagediscount(drink mondays are buy one get one free burger nights rules appendruleand(todayis(monday)numbe...
8,112
interpreter pattern parting shots wherever you are on your programming journeydecide right now that you will do the hard work needed to become better you do this by working on programming projects and doing programming challenges one such challenge by jeff bay can be found in thought works anthologypublished by the pr...
8,113
interpreter pattern implement your dsl from the previous exercise in python so it can interpret to-do items and extract the necessary characteristics build basic to-do list application using one of the popular python web frameworks and have it interpret to-do' using your dsl interpreter find some interesting improvemen...
8,114
iterator pattern the wheels of the bus go round and roundround and roundround and round data structures and algorithms form an integral part of the software design and development process oftendifferent data structures have different usesand using the right data structure for specific problem might mean lot less work a...
8,115
iterator pattern print(node dataif node right is not nonetree_traverse(node rightif __name__ ="__main__"root node(" am the root"root left node("first left child"root right node("first right child"root left right node("right child of first left child of root"tree_traverse(rootcontrast this to when you want to traverse s...
8,116
iterator pattern firstwe define an interface that defines function that gets the next item in the collectionand another function to alert some external function that there are no more elements left in the collection to return secondwe define some sort of object that can use the interface to traverse the collection this...
8,117
iterator pattern def getiterator(self)return mylistiterator(selfif __name__ ="__main__"my_list mylist( my_iterator my_list getiterator(while my_iterator has_next()print(my_iterator next()this prints out the following result this idea of traversing some collection is so widespread that it has name--the iterator pattern ...
8,118
iterator pattern python uses two specific method calls and one raised exception to provide the iterator functionality throughout the language the first method of an iterable is the __iter__(methodwhich returns an iterator object nexta __next__(method must be provided by the iterator objectit is used to return the next ...
8,119
iterator pattern if we were to implement the binary tree we saw at the beginning of this as python iterableit would be implemented as followsbin_tree_iterator py class node(object)def __init__(selfdata)self data data self left none self right none class mytree(object)def __init__(selfroot)self root root def add_node(se...
8,120
iterator pattern while current left is not nonecurrent current left self stack append(currentreturn self def __next__(self)if len(self stack< raise stopiteration while len(self stack current self stack pop(data current data if current right is not nonecurrent current right self stack append(currentwhile current left is...
8,121
iterator pattern we keep the node class exactly as we defined it earlieronly now we have added container classnamely mytree this class implements the iterator protocoland as such can be used in normal python for loopas we have seen in the list iterator we also included convenience function that allows us to build binar...
8,122
iterator pattern if __name__ ="__main__"tree mytree(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )for in treeprint(iprint("maximum value{}format(max(tree))print("total of values{}format(sum(t...
8,123
iterator pattern if __name__ ="__main__"tree mytree(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )print([ for in tree]resulting in an ordered list of values [ list comprehensions are fairly s...
8,124
iterator pattern itertools ' sure you are convinced of the usefulness of iterators by now soi will add quick mention of the itertools package included in the standard library it contains number of functions that allow you to combine and manipulate iterators in some interesting ways these building blocks have been take...
8,125
iterator pattern every time the cycler reaches the last elementit just starts back at the beginning the third and final function you can look at is zip_longest()which combines set of iterables and returns their matched elements on each iteration zip_longest example import itertools list [ list [' '' '' 'zipped itertool...
8,126
iterator pattern gen_ func py def gen_squares( ) while nyield * print("next " + if __name__ ="__main__" gen_squares( print( __next__()print( __next__()print( __next__()print( __next__()print( __next__()the result you get from requesting next is the next squareas you can see here next next next next traceback (most rece...
8,127
iterator pattern when the interpreter encounters the yield statementit keeps record of the current state of the function and returns the value that is yielded once the next value is requested via the __next__(methodthe internal state is loaded and the function continues from where it left off generators are great way t...
8,128
iterator pattern parting shots iterators and generators will help you do lot of heavy lifting as you explore the world of pythonand getting comfortable using them will help you code faster they also extend your code into the realm of functional programmingwhere you are more focused on defining what the program must do...
8,129
observer pattern you knownortoni've been watching you --eddie murphydelirious if you did the object calisthenics exercise from you would have noticed how difficult it is to reduce the number of lines used in certain methods this is especially difficult if the object is too tightly coupled with number of other objectsi ...
8,130
observer pattern def complete(self)self user add_experience( self user wallet increase_balance( for badge in self user badgesif self _type =badge _typebadge add_points( class user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experience +amount def __s...
8,131
observer pattern class badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self points self awarded true def __str__(self)if self awardedaward_string "earnedelseaward_string "unearnedreturn "{}{[{}]formatself nameaward_s...
8,132
observer pattern in the outputwe can see the relevant values added to the walletexperienceand badgeswith the right badge being awarded once the threshold is cleared wallet experience badges fun badgeearned [ bravery badgeunearned [ missing badgeunearned [ +++++++++++++++this very basic implementation has fairly complex...
8,133
observer pattern class user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experience +amount def complete_task(selftask)self add_experience( def __str__(self)return "wallet\ {}\nexperience\ {}\nbadges +\ {} ++++++++++++++++formatself walletself experi...
8,134
observer pattern class badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self points self awarded true def complete_task(selftask)if task _type =self _typeself add_points( def __str__(self)if self awardedaward_string "...
8,135
observer pattern tasks [task(user )task(user )task(user )for task in taskstask complete(print(userif __name__ ="__main__"main(this results in the same output as before this is already much better solution the evaluation now takes place in the objects where they are relevantwhich is closer to the rules contained in the ...
8,136
observer pattern class user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experience +amount def complete_task(selftask)self add_experience( def __str__(self)return "wallet\ {}\nexperience\ {}\nbadges +\ {}\ ++++++++++++++++formatself walletself exper...
8,137
observer pattern class badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self points self awarded true def complete_task(selftask)if task _type =self _typeself add_points( def __str__(self)if self awardedaward_string "...
8,138
observer pattern tasks [task(user )task(user )task(user )for task in taskstask complete(print(userif __name__ ="__main__"main(now you have list of objects to be called back when the task is completedand the task need not know anything more about the objects in the callbacks list other than that they have complete_task(...
8,139
observer pattern class concreteobserver(observer)def update(selfobserved)print("observingobservedclass observable(object)def __init__(self)self observers set(def register(selfobserver)self observers add(observerdef unregister(selfobserver)self observers discard(observerdef unregister_all(self)self observers set(def upd...
8,140
observer pattern def unregister(selfobserver)self observers discard(observerdef unregister_all(self)self observers set(def update_all(self)for observer in self observersobserver update(selfin the preceding codethe observable keeps record of all the objects observing it in list called observersand whenever relevant chan...
8,141
observer pattern def unregister_all(self)self callbacks set(def update_all(self)for callback in self callbackscallback(selfdef main()observed observable(observer concreteobserver(observed register(lambda xobserver update( )observed update_all(if __name__ ="__main__"main(although there are many ways to string up the act...
8,142
observer pattern class observable(object)def __init__(self)self callbacks set(self changed false def register(selfcallback)self callbacks add(callbackdef unregister(selfcallback)self callbacks discard(callbackdef unregister_all(self)self callbacks set(def poll_for_change(self)if self changedself update_all def update_a...
8,143
observer pattern mentioned couplingso let me clarify what is meant when we talk about coupling generallywhen we talk about the level of coupling between objectswe refer to the degree of knowledge that one object needs with regard to other objects that it interacts with the more loosely objects are coupledthe less knowl...
8,144
observer pattern def unregister(selfobserver)self observers discard(observerdef unregister_all(self)self observers set(def update_all(self)for observer in self observersobserver update(selfclass user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experi...
8,145
observer pattern def decrease_balance(selfamount)self amount -amount def update(selfobserved)self increase_balance( def __str__(self)return str(self amountclass badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self po...
8,146
observer pattern def main()wallet wallet(user user(walletbadges badge("fun badge" )badge("bravery badge" )badge("missing badge" user badges extend(badgestasks [task(user )task(user )task(user )for task in taskstask register(wallettask register(userfor badge in badgestask register(badgefor task in taskstask update_all(p...
8,147
observer pattern exercises use the observer pattern to model system where your observers can subscribe to stocks in stock market and make buy/sell decisions based on changes in the stock price implement the flag for changed on an example with the object set of observers
8,148
state pattern under pressure --queen"under pressurea very useful tool for thinking through software problems is the state diagram in state diagramyou construct graphwhere nodes represent the state of the system and edges are transitions between one node in the system and another state diagrams are useful because they l...
8,149
state pattern rejecting pin getting transaction selection set of states for every part of every transaction finalizing transaction returning card printing slip dispensing slip specific system and user actions will cause the atm to move from one state to the next inserting card into the machine will cause the machine to...
8,150
state pattern win addstr( ""win move( while truech win getch(if ch is not nonewin move( win deleteln(win addstr( ""if ch = break elif ch = print("running left"elif ch = print("running right"elif ch = print("jumping"elif ch = print("crouching"elseprint("standing"time sleep( if __name__ ="__main__"main(as an exerciseyou ...
8,151
state pattern state pattern on an abstract levelall object-oriented systems concern themselves with the actors in system and how the actions of each impact the other actors and the system as whole this is why state machine is so helpful in modeling the state of an object and the things that cause said object to react ...
8,152
state pattern def switch_state(self)self state_machine state self state_machine state class statemachine(object)def __init__(self)self state concretestate (selfself state concretestate (selfself state self state def switch(self)self state switch_state(def __str__(self)return str(self statedef main()state_machine statem...
8,153
state pattern thatfor given inputthe machine transitions to the correct subsequent state python includes very solid unit-testing frameworknot surprisingly called unittest to test our generic state machinewe could use the following codeimport unittest class genericstatepatterntest(unittest testcase)def setup(self)self s...
8,154
state pattern import curses import time class state(object)def __init__(selfstate_machine)self state_machine state_machine def switch(selfin_key)if in_key in self state_machine mappingself state_machine state self state_machine mapping[in_keyelseself state_machine state self state_machine mapping["default"class standi...
8,155
state pattern self jumping jumping(selfself crouching crouching(selfself mapping " "self running_left" "self running_right" "self crouching" "self jumping"default"self standingself state self standing def action(selfin_key)self state switch(in_keydef __str__(self)return str(self statedef main()player statemachine(win c...
8,156
state pattern player action(chr(ch)print(player statetime sleep( if __name__ ="__main__"main(how do you feel about the altered codewhat do you like about itwhat have you learnedwhat do you think can be improvedi want to encourage you to begin looking at code online and asking yourself these questions you will often fin...
8,157
state pattern implement set of transition methods to deal with the expected inputs for every state implement the actions that need to be taken by the machine in every state rememberthese actions live in the concrete state class as well as in the base state class there you have it-- fully implemented state machine that ...
8,158
strategy pattern move in silenceonly speak when it' time to say checkmate --unknown from time to timeyou might find yourself in position where you want to switch between different ways of solving problem you essentially want to be able to pick strategy at runtime and then run with it each strategy might have its own se...
8,159
strategy pattern this solution results in the followingstrategy not implemented - this is what we want sadlywe suffer from the same problem we encountered in previous namely that whenever we want to add another strategy to the reducerwe have to add another elif statement to the function together with another block of c...
8,160
strategy pattern def main()no_strategy strategyexecutor(addition_strategy strategyexecutor(additionstrategy()subtraction_strategy strategyexecutor(subtractionstrategy()no_strategy execute( addition_strategy execute( subtraction_strategy execute( if __name__ ="__main__"main(this again results in the required outputstrat...
8,161
strategy pattern def strategy_addition(arg arg )print(arg arg def strategy_subtraction(arg arg )print(arg arg def main()no_strategy strategyexecutor(addition_strategy strategyexecutor(strategy_additionsubtraction_strategy strategyexecutor(strategy_subtractionno_strategy execute( addition_strategy execute( subtraction_s...
8,162
strategy pattern def main()executor( executor( strategy_additionexecutor( strategy_subtractionif __name__ ="__main__"main(as beforeyou can see that the output matches the requirementstrategy not implemented - we created function that could take pair of arguments and strategy to reduce them at runtime multiplication or ...
8,163
strategy pattern def strategy_subtraction(arg arg )return arg arg def main()print(executor( )print(executor( strategy_addition)print(executor( strategy_subtraction)if __name__ ="__main__"main(once againwe test that the code results in the output we saw throughout this strategy not implemented - indeed it does now we ha...
8,164
strategy pattern up your sleeves and knock out that fix you had in mind the next poor coder who has to work on this code might just be youand then you will thank the coder who came before and cleaned things up little exercises see if you can implement maze generator that will print maze using "#and to represent walls ...
8,165
template method pattern success without duplication is merely future failure in disguise --randy gage in how to build multi-level money machinethe science of network marketing in lifeas in codingthere are patternssnippets of actions that you can repeat step by step and get the expected result in more complex situations...
8,166
template method pattern what are we to do when we identify solid pattern of actions that need to be taken in variety of contextseach with its own nuancesfunctions are one form of recipe consider the pattern for calculating !where nn - where else nis solving this for the case where we could simply writefact_ that is fin...
8,167
template method pattern you sit down and identify the steps needed to integrate with the remote system sync stock items between the point of sale and the third-party system send transactions to the third party this is simplified set of stepsbut it will serve us well enough in the world of simple functions we had before...
8,168
template method pattern the result looks something like thisrunning stock sync between local and remote system retrieving remote stock items updating local items sending updates to third party send transaction{'items'[{'amount_purchased' 'item_id' 'value' }]'id' nextwe will evaluate the code in terms of what happens i...
8,169
template method pattern def send_transaction(transactionsystem)if system ="system "print("send transaction to system { ! }format(transaction)elif system ="system "print("send transaction to system { ! }format(transaction)elif system ="system "print("send transaction to system { ! }format(transaction)elseprint("no valid...
8,170
template method pattern not only do you have to pass in the arguments needed to execute the specific functionalitybut also you have to pass around the name of the service relevant to the current user of the system it is also obvious from our previous discussions that this way of building system of any non-trivial scale...
8,171
template method pattern def send_transaction_strategy_system (transaction)print("send transaction to system { ! }format(transaction)def main()transaction "id" "items""item_id" "amount_purchased" "value" ]}print("="* sync_stock_items(stock_sync_strategy_system send_transactiontransactionsend_transaction_strategy_system ...
8,172
template method pattern we have the same results with the test cases included in the main function as we had for the version using multiple if statements =========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send ...
8,173
template method pattern in the most general sensethe template method pattern will look something like this when implementedimport abc class templateabstractbaseclass(metaclass=abc abcmeta)def template_method(self)self _step_ (self _step_ (self _step_n(@abc abstractmethod def _step_ (self)pass @abc abstractmethod def _s...
8,174
template method pattern nowlet' use this idea to implement our third-party integrations using the template method pattern import abc class thirdpartyinteractiontemplate(metaclass=abc abcmeta)def sync_stock_items(self)self _sync_stock_items_step_ (self _sync_stock_items_step_ (self _sync_stock_items_step_ (self _sync_st...
8,175
template method pattern def _sync_stock_items_step_ (self)print("sending updates to third party system "def _send_transaction(selftransaction)print("send transaction to system { ! }format(transaction)class system (thirdpartyinteractiontemplate)def _sync_stock_items_step_ (self)print("running stock sync between local an...
8,176
template method pattern def main()transaction "id" "items""item_id" "amount_purchased" "value" ]}for in [system system system ]print("="* system (system sync_stock_items(system send_transaction(transactionif __name__ ="__main__"main(once againour test code results in the output we would hope for as in the previous sect...
8,177
template method pattern send transaction to system ({'items'[{'amount_purchased' 'value' 'item_id' }]'id' },=========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'amount_pur...
8,178
template method pattern think of some other systems where you know what steps you need to takebut the specifics of what gets done in each of these steps differ from case to case implement basic template pattern-based system to model the situation you thought of in the previous exercise
8,179
visitor pattern want to believe -- -files since python can be found in many placesyou might one day want to do little bit of home automation get couple of single-board and micro computers and connect them to some hardware sensors and actuatorsand soon you have network of devicesall controlled by you each of these items...
8,180
visitor pattern cannot be reached the thermostat might return the actual temperature it is reading and none if it is offline the front door lock is similar to the lightswith being locked unlockedand - error the coffee machine has states for erroroffonbrewingwaitingand heating using integers from - to respectively the t...
8,181
visitor pattern class coffeemachine(object)def _init_(self)pass def get_status(self)return random choice(range(- , )class clock(object)def __init__(self)pass def get_status(self)return "{}:{}format(random randrange( )random randrange( )def main()device_network thermostat()temperatureregulator()doorlock()coffeemachine()...
8,182
visitor pattern this is lot cleaner than the types of output you will encounter in the real worldbut this is good representation of the messy nature of real-world devices we now have simulation of network of devices we can move on to the parts we are really interested innamely doing something with these devices the fir...
8,183
visitor pattern def get_status(self)return random choice(['heating''cooling''on''off''error']def is_online(self)return self get_status(!'errorclass doorlock(object)def __init__(selfname)self name name def get_status(self)return random choice(range(- , )def is_online(self)return self get_status(!- class coffeemachine(ob...
8,184
visitor pattern def main()device_network thermostat("general thermostat")temperatureregulator("thermal regulator")doorlock("front door lock")coffeemachine("coffee machine")light("bedroom light")light("kitchen light")clock("system clock")for device in device_networkprint("{is online\ {}format(device namedevice is_online...
8,185
visitor pattern one other thing that you should note is that we now import the testcase class from the unittest librarywhich allows us to write tests to make sure thatafter applying the boot sequence to devicethat device is indeed in the state we expect it to be this is not an in-depth tutorial on unit testingbut will ...
8,186
visitor pattern class temperatureregulator(object)def __init__(selfname)self name name self status self get_status(def get_status(self): return random choice(['heating''cooling''on''off''error']def is_online(self)return self status !'errordef boot_up(self)self status 'onclass doorlock(object)def __init__(selfname)self ...
8,187
visitor pattern class clock(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return "{}:{}format(random randrange( )random randrange( )def is_online(self)return true def boot_up(self)self status " : class homeautomationboottests(unittest testcase)def setup(self)self thermostat...
8,188
visitor pattern def test_boot_light_turns_it_off(self)self bedroom_light boot_up(self assertequal(self bedroom_light status def test_boot_system_clock_zeros_it(self)self system_clock boot_up(self assertequal(self system_clock status" : "if __name__ ="__main__"unittest main(setting the execution function for when the pr...
8,189
visitor pattern def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)self status def update_status(selfperson_ _homeperson_ _home)if person_ _homeif person_ _homeself status elseself status elif person_ _homeself status elseself status class thermostat(object)def...
8,190
visitor pattern class temperatureregulator(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(['heating''cooling''on''off''error']def is_online(self)return self status !'errordef boot_up(self)self status 'ondef update_status(selfperson_ _homeperson_ _home)if...
8,191
visitor pattern def update_status(selfperson_ _homeperson_ _home)if person_ _homeself status elif person_ _homeself status elseself status class coffeemachine(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status...
8,192
visitor pattern def get_status(self)return "{}:{}format(random randrange( )random randrange( )def is_online(self)return true def boot_up(self)self status " : def update_status(selfperson_ _homeperson_ _home)if person_ _homeif person_ _homepass else" : elif person_ _home" : elsepass as an exercisewrite tests for these s...
8,193
visitor pattern it is necessary to mention martin fowler' take on developing micro service-based architectures fowler posits that one first has to develop the monolith because at the outset you do not know which elements will coalesce to form good micro services and which can be kept separate as you work on and grow sy...
8,194
visitor pattern look at the generic implementation of the visitor pattern and get feel for the code we will dig into the details after this code snippet import abc class visitable(object)def accept(selfvisitor)visitor visit(selfclass compositevisitable(visitable)def __init__(selfiterable)self iterable iterable def acce...
8,195
visitor pattern import abc import random import unittest class visitable(object)def accept(selfvisitor)visitor visit(selfclass compositevisitable(visitable)def __init__(selfiterable)self iterable iterable def accept(selfvisitor)for element in self iterableelement accept(visitorvisitor visit(selfclass abstractvisitor(ob...
8,196
visitor pattern class lightstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)if self person_ _homeif self person_ _homeelement status elseelement status elif self person_ _homeelement status elseelement...
8,197
visitor pattern class temperatureregulator(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(['heating''cooling''on''off''error']def is_online(self)return self status !'errordef boot_up(self)self status 'onclass temperatureregulatorstatusupdatevisitor(ab...
8,198
visitor pattern def is_online(self)return self status !- def boot_up(self)pass class doorlockstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)if self person_ _homeelement status elif self person_ _home...
8,199
visitor pattern def visit(selfelement)if self person_ _homeif self person_ _homeelement status elseelement status elif self person_ _homeelement status elseelement status class clock(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)return "{}:{}format(random randrange( )ran...