id
int64
0
25.6k
text
stringlengths
0
4.59k
8,200
visitor pattern element status " : elif self person_ _homeelement status " : elsepass class compositevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)tryc eval("{}statusupdatevisitorformat (element __class__ __name__)exceptprint("visitor for {not foundformat (element __class__ __name__)elsevisitor (self person_ _homeself person_ _homevisitor visit(elementclass myhomesystem(compositevisitable)pass class myhomesystemstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)pass class homeautomationboottests(unittest testcase)def setup(self)self my_home_system myhomesystem(thermostat("general thermostat")temperatureregulator("thermal regulator")
8,201
visitor pattern doorlock("front door lock")coffeemachine("coffee machine")light("bedroom light")clock("system clock")]def test_person_ _not_home_person_ _not_home(self)expected_state mapstrself my_home_system iterable[ status'off' self my_home_system iterable[ status self visitor compositevisitor(falsefalseself my_home_system accept(self visitorretrieved_state sorted([str( statusfor in self my_home_system iterable]self assertequal(retrieved_statesorted(expected_state)def test_person_ _home_person_ _not(self)expected_state mapstrself my_home_system iterable[ status'heating' " :
8,202
visitor pattern self visitor compositevisitor(truefalseself my_home_system accept(self visitorretrieved_state sorted([str( statusfor in self my_home_system iterable]self assertequal(retrieved_statesorted(expected_state)def test_person_ _not_home_person_ _home(self)expected_state mapstrself my_home_system iterable[ status'cooling' " : self visitor compositevisitor(falsetrueself my_home_system accept(self visitorretrieved_state sorted([str( statusfor in self my_home_system iterable]self assertequal(retrieved_statesorted(expected_state)def test_person_ _home_person_ _home(self)expected_state mapstrself my_home_system iterable[ status'on' self my_home_system iterable[ status
8,203
visitor pattern self visitor compositevisitor(truetrueself my_home_system accept(self visitorretrieved_state sorted([str( statusfor in self my_home_system iterable]self assertequal(retrieved_statesorted(expected_state)if __name__ ="__main__"unittest main( have just couple of notes on the preceding code firstif you are taking input from userneverever use the eval functionas python blindly executes whatever is in the string passed to eval secondwe are choosing to balance the general nature of eval by using the name of the class to be visitedwhich is not the best way in pythonas now you rely on naming conventions and magicwhich is not explicit stillyou could implement the pattern if you were thinking state machine might help the situationyou are not wrong this brings us to something that would seem obvious once you read itbut might not be so obvious from the get-goand that is the fact that you can use more than one design pattern in single implementation in this caseit should be clear that the state of the house resembles state machine we have four statesperson is not homeperson is not home person is not homeperson is home person is homeperson is not home person is homeperson is home whenever person either leaves or arrives at home the state of the system changes soimplementing state machine for the visitor seems like good idea try implementing the state pattern on the previous code snippet as an exercise when you separate the data structures in the system from the algorithms that operate on themyou gain an added benefit you can adhere to the open-closed principle much more easily this principle sees you write code where your objects are open to extension (using inheritancebut closed to alteration (by setting or changing values in an object or altering the methods on an objectlike the dry and yagni principlesthe open-closed principle serves as guiding light as you plan and develop system violations of these principles also serve as an early-warning system that you are writing unmaintainable code that will come back and hurt you down the line
8,204
visitor pattern parting shots sometimes you just need to write codeso type out the example line by line to get feel for the idea expressed whenever find descriptions of an algorithm or idea that do not quite understand from the way it is describedi reach for this tool there is something different that happens when you get down and write out the code rather than just reading it oftennuances that were not clear before get exposed when working your way through the code with design patterns that you find complicated or high-level algorithmsi suggest typing out the generic versionthen typing out some specific implementationand finally altering some details to fit your own example beyond those in the text you are looking at finallyimplement the pattern or algorithm from scratch for specific instance this type of work is usually not the fun part of programmingbut it is the deliberate practice that you need to do in order to become better programmer there is whole world of ideas to explore once you get past the simple elements of syntax and the more general outline of writing idiomatic python that world is where you move from being able to write words in the languageor being able to string sentences togetherto expressing ideas in code in the long runthat is what you want to get better at--the process of expressing your thoughts and reasoning in pythonour language of choice for this book as with all forms of expressionyou will get better the more you do itbut only if you challenge yourself you can even use this process to explore new libraries where the documentation is lacking or opaque you could begin by exploring what tests are included in the repositoryandfailing to make enough headway through thatyou could type your way through some of the key methods and classes in the library not only will you get better idea of what is going on and how the library should be usedbut you might also pick up couple of interesting ideas that you could explore further in the endas with all ideastry them on and see where they work and where they let you down keep what fits your brain and discard what trips you upas long as you only discard an idea after you have gained clarityand not while you still find it hard
8,205
visitor pattern exercises use the process from the "parting shotssection and code your way to deeper understanding of the visitor patternif you have not been doing so throughout the book find an interesting python package in the standard library and code through thatseeing how these developers do things differently from you write the tests for these states where person and person are either there or not make sure you cover all the possible options in these tests extend the code in each instance to accommodate friends coming over for social gathering think about the other design patterns in this bookare there other ones that would make the code betterif soimplement the solution using this design pattern in order to crystallize the reason why the visitor pattern makes adhering to the open-closed principle easieryou are going to add another device to our system-- streaming media entertainment center this device comes with python bindingsbut we do not have access to the inner workings of the device for some reason add this object to our network and define dummy interface to mimic the interface provided thenadd custom settings for each of the states in the home add the state pattern to the final piece of code in this to allow you to handle the four scenarios we discussed how do you need to think differently about the code we wrote in the thendecide if implementing the state patternin this casemakes the solution better or worse think specifically about maintenance and the principles we talked about thus far
8,206
model-view-controller pattern alwaysworlds within worlds --clive barkerweaveworld not far along in your journey as programmeryou begin to see some other patterns emerge--more like patterns of patterns like this one most if not all programs consist of some sort of external action that initiates the program the initiating action may or may not have databut if it doesthe program consumes that datasometimes persisting itsometimes not finallyyour program has an effect on the world that' itbasicallyall programs you will ever encounter will have this pattern let me give you simple example and then one that you might not see from the start the first example is that of visitor signing up to receive email updates from website it does not matter how the user enters the informationas from the system' perspective everything begins with post request hitting the program the request contains name and email address now the program is initiated as in the preceding exampleand we have some extra data the program goes through the process of checking if the email is already in the database if notit is persisted together with the name of the visitor if it isthen no further action is taken finallythe system returns status code alerting the calling program that everything went as expected note that there are two places where the program changes the world outside of the execution of the program itselfnamely the database and the response to the calling system we could also look at gamewhere you have the game in some state and the player interacts with the game via the keyboard and mouse these peripheral actions are translated into commands by the game enginethe commands are processedand the game state updateswhich is relayed back to the player in terms of visualaudioand possible tactile feedback the process remains the sameinputprocessoutput (cwessel badenhorst badenhorstpractical python design patterns
8,207
model-view-controller pattern seeing programs in this way helpssince you become better at asking questions about what happens at each step in the process sadlythis view is too general and leaves too much outand thus it is not completely helpful when it comes to the actual nuts and bolts development work stillit is useful tool to have this book is called practical python design patternsand not abstract programming modelsso let' get practical without completely discarding the idea of the three parts of programdifferent types of programs take different perspectives on the idea games execute game loopwhile web applications take user input and use that input together with some form of stored data to produce an output to be displayed in the user' browser window for the sake of this we are going to use command-line dummy program to demonstrate the ideas want you to internalize once you have clear grasp of the basic ideaswe will implement themusing couple of python libraries to build basic web application that can serve web pages from your local machine our first program will simply take name as an argument if the name is already storedit will welcome the visitor backotherwiseit will tell the visitor that it is nice to meet them import sys def main(name)trywith open('names dat'' 'as data_filenames [ for in data_file readlines()except filenotfounderror as ewith open('names dat'' 'as data_filedata_file write(namenames [if name in namesprint("welcome back {}!format(name)elseprint("hi {}it is good to meet youformat(name)with open('names dat'' 'as data_filedata_file write(name
8,208
model-view-controller pattern if __name__ ="__main__"main(sys argv[ ]the program uses the sys package in the standard library to expose the arguments passed to the program the first argument is the name of the script being executed in our example programthe first additional argument that is expected is the name of person we have some checks includedensuring that some string was in fact passed to the program nextwe check if the program encountered the name previouslyand it displays the relevant text nowfor all the reasons discussed throughout the bookwe know that this is not good the script is doing too much in the main functionso we proceed to decompose it into different functions import sys import os def get_append_write(filename)if os path exists(filename)return 'areturn 'wdef name_in_file(filenamename)if not os path exists(filename)return false return name in read_names(filenamedef read_names(filename)with open(filename' 'as data_filenames data_file read(split('\ 'return names def write_name(filenamename)with open(filenameget_append_write(filename)as data_filedata_file write("{}\nformat(name)def get_message(name)if name_in_file('names dat'name)return "welcome back {}!format(name
8,209
model-view-controller pattern write_name('names dat'namereturn "hi {}it is good to meet youformat(namedef main(name)print(get_message(name)if __name__ ="__main__"main(sys argv[ ] ' sure you suspect that there is more to come in terms of cleaning up this codeso why go through this process againthe reason for following these steps is that want you to get feel for when you need to deconstruct function or method if all programs stayed the way they were planned in the beginning of the projectthis sense of when and how to break things into smaller parts would not be needed following the same logicthe process is incremental you might start out like we didbreaking the program into functions after whilethe program grows significantlyand now the single file becomes burdena good sign that you need to break the one file program into separate files but how will you do thatwe will see as we grow our initial program they say always be youunless you can be lionin which case always be lion soin that spiritwe will now extend the program to display special message for certain argumentsspecifically lion import sys import os def get_append_write(filename)if os path exists(filename)return 'areturn 'wdef name_in_file(filenamename)if not os path exists(filename)return false return name in read_names(filenamedef read_names(filename)with open(filename' 'as data_filenames data_file read(split('\ '
8,210
model-view-controller pattern return names def write_name(filenamename)with open(filenameget_append_write(filename)as data_filedata_file write("{}\nformat(name)def get_message(name)if name ="lion"return "rrrrrrrroar!if name_in_file('names dat'name)return "welcome back {}!format(namewrite_name('names dat'namereturn "hi {}it is good to meet youformat(namedef main(name)print(get_message(name)if __name__ ="__main__"main(sys argv[ ]nowwe finally begin to see another pattern appear what we have here are three distinct types of functionswhich are the result of separating the concerns as much as we can we end up with code that deals with getting the greeting to returncode writing the greeting to the consoleand some code to handle the flow of the programsending the relevant requests to the data-retrieval codegetting the greetingand sending that to the code that ultimately displays it on the console model-view-controller skeleton in general termswe want to capture the pattern discussed in the previous paragraph in reusable pattern we also want to bake the open-closed principle into the codeandto that endwe want to encapsulate key parts of the program in objects before anything can happenour program must receive some form of request this request must be interpreted and then kick off the relevant actions all of this happens inside an object that exists solely for controlling the flow of the program this object handles actions like requesting datareceiving dataand dispatching responses to the
8,211
model-view-controller pattern command line the object in question is all about controlandunsurprisinglyobjects of this class are called controllers they are the glue that holds the system togetherand usually the place where the most action takes place here are the control functions from our previous program controller_ functions py def name_in_file(filenamename)if not os path exists(filename)return false return name in read_names(filenamedef get_message(name)if name_in_file('names dat'name)return "welcome back {}!format(namewrite_name('names dat'namereturn "hi {}it is good to meet youformat(nameif __name__ ="__main__"main(sys argv[ ]these are not yet encapsulated in an objectbut at least they are in one place nowlet' proceed with the next part of the systemgrouping functions as we go before we return to them and clean up the parts once request is received and the controller decides what must happen to the requestsome data from the system is needed since we are dealing with the grouping together of code that shares functionalitywe will now grab all the functions that have anything to do with the retrieval of data and place them into function file oftenthe structural representation of data is referred to as data modeland so the part of the program that deals with the data is called the model here are the model functions from our previous program model_ functions py def get_append_write(filename)if os path exists(filename)return '
8,212
model-view-controller pattern return 'wdef read_names(filename)with open(filename' 'as data_filenames data_file read(split('\ 'return names def write_name(filenamename)with open(filenameget_append_write(filename)as data_filedata_file write("{}\nformat(name)once the code is encapsulated into an objectyou will find that as program grows different types of data are requiredand each of these gets placed into its own model object usuallymodel objects each end up in their own file what remains is the code that is focused on delivering some sort of information back to the user in our casethis is done via the standard output port to the console thisas you have guessed by nowis called the view code here are the remaining view functions from our previous program view_ functions py def main(name)print(get_message(name)as am certain you noticedthe grouping of functions is not as clear-cut as we would like it to be ideallyyou should be able to change anything in either one of the groups of functions (without changing their interfaces)and this should not have any effect on the other modules before we make clean split and encapsulate the three classes of functions into separate classeslet' look at the elements that go into the pattern controllers the controller is the heart of the patternthe part that marshalls all the other classes users interact with the controllerand through it the whole system the controller takes the user inputhandles all the business logicgets data from the modeland sends the data to the view to be transformed into the representation to be returned to the user
8,213
model-view-controller pattern class genericcontroller(object)def __init__(self)self model genericmodel(self view genericview(def handle(selfrequest)data self model get_data(requestself view generate_response(datamodels models deal with datagetting datasetting dataupdating dataand deleting data that' it you will often see models doing more than thatwhich is mistake your models should be program-side interface to your data that abstracts away the need to directly interact with the data storeallowing you to switch from file-based store to some keyvalue store or full-on relational database system oftena model will contain the fields used as attributes on the objectallowing you to interact with the database as with any other objectwith some sort of save method to persist the data to the data store our genericmodel class contains only simple method to return some form of data class genericmodel(object)def __init__(self)pass def get_data(selfrequest)return {'request'requestviews as with modelsyou do not want any business logic in your views views should only deal with the output or rendering of data passed to it into some sort of format to be returned to the userbe that print statements to the console or render to the player of game the format of the output does not make major difference in what the view does you will also be tempted to add logic to the viewthis is slippery slope and not path you should head down
8,214
model-view-controller pattern the following is simple genericview class that you can use as base for building your own viewsbe they for returning json to an http call or plotting graphs for data analysis class genericview(object)def __init__(self)pass def generate_response(selfdata)print(databringing it all together finallyhere is full program using the modelviewand controller to give you an idea of how these elements interact import sys class genericcontroller(object)def __init__(self)self model genericmodel(self view genericview(def handle(selfrequest)data self model get_data(requestself view generate_response(dataclass genericmodel(object)def __init__(self)pass def get_data(selfrequest)return {'request'requestclass genericview(object)def __init__(self)pass
8,215
model-view-controller pattern def generate_response(selfdata)print(datadef main(name)request_handler genericcontroller(request_handler handle(nameif __name__ ="__main__"main(sys argv[ ]now that we have clear picture of what each of the object classes should look likelet' proceed to implement the code in our example for this in terms of these object classes as we have done thus farwe will lead with the controller object controller py import sys from model import namemodel from view import greetingview class greetingcontroller(object)def __init__(self)self model namemodel(self view greetingview(def handle(selfrequest)if request in self model get_name_list()self view generate_greeting(name=requestknown=trueelseself model save_name(requestself view generate_greeting(name=requestknown=falsedef main(main)request_handler greetingcontroller(request_handler handle(nameif __name__ ="__main__"main(sys argv[ ]
8,216
model-view-controller pattern nextwe create the model object that retrieves greeting from file or returns the standard greeting model py import os class namemodel(object)def __init__(self)self filename 'names datdef _get_append_write(self)if os path exists(self filename)return 'areturn 'wdef get_name_list(self)if not os path exists(self filename)return false with open(self filename' 'as data_filenames data_file read(split('\ 'return names def save_name(selfname)with open(self filenameself _get_append_write()as data_filedata_file write("{}\nformat(name)lastlywe create view object to display the greeting to the user view py class greetingview(object)def __init__(self)pass def generate_greeting(selfnameknown)if name ="lion"print("rrrrrrrroar!"return
8,217
model-view-controller pattern if knownprint("welcome back {}!format(name)elseprint("hi {}it is good to meet youformat(name)greatif you want to make requeststart the program like thispython controller py your_name the first time you run this scriptthe responseas expectedlooks like thishi your_nameit is good to meet you before we go oni want you to see why this is such great idea let' say we grow our programand at some time we decide to include different types of greetings that depend on the time of day to do thiswe can add time model to the systemwhich would then retrieve the system time and decide if it is morningafternoonor evening based on the time this information is sent along with the name data to the view to generate the relevant greeting controller py class greetingcontroller(object)def __init__(self)self name_model namemodel(self time_model timemodel(self view greetingview(def handle(selfrequest)if request in self name_model get_name_list()self view generate_greetingname=requesttime_of_day=self time_model get_time_of_day()known=true elseself name_model save_name(requestself view generate_greetingname=request
8,218
model-view-controller pattern time_of_day=self time_model get_time_of_day()known=false view py class greetingview(object)def __init__(self)pass def generate_greeting(selfnametime_of_dayknown)if name ="lion"print("rrrrrrrroar!"return if knownprint("good {welcome back {}!format(time_of_dayname)elseprint("good {{}it is good to meet youformat(time_of_dayname)models py class namemodel(object)def __init__(self)self filename 'names datdef _get_append_write(self)if os path exists(self filename)return 'areturn 'wdef get_name_list(self)if not os path exists(self filename)return false with open(self filename' 'as data_filenames data_file read(split('\ 'return names
8,219
model-view-controller pattern def save_name(selfname)with open(self filenameself _get_append_write()as data_filedata_file write("{}\nformat(name)class timemodel(object)def __init__(self)pass def get_time_of_day(self)time datetime datetime now(if time hour return "morningif <time hour return "afternoonif time hour > return "eveningalternativelywe could use database to store the greetings instead of saving them in different files the beauty of it all is that it does not matter to the rest of the system what we do in terms of storage just to illustrate this factwe will alter our model to store the greeting in json file rather than in plain text implementing this functionality will require the json package in the standard library the hardest part of adapting this approach to programming is that you have to decide what goes where how much do you place in the modelor what level of processing goes into the viewherei like the concept of fat controllers and skinny models and views we want models to just deal with the creationretrievalupdatingand deletion of data views should only concern themselves with displaying data everything else should sit in the controller sometimesyou might implement helper classes for the controllerand that is goodbut do not let yourself get tempted into doing more than you should in model or view classic example of model doing too much is having one model that requires another modellike having userprofile class that requires user class so you know which user the profile belongs to the temptation is there to send all the information to the userprofile model' constructor and have it create the user instance on the flyit is all data after all that would be mistakeas you would have the model controlling some of the flow of the programwhich should rest on the controller and its helper classes much better
8,220
model-view-controller pattern solution would be to have the controller create the user instance and then force it to pass the user object to the constructor of the userprofile model class the same problems could arise on the view side of the picture the key thing to remember is that every object should have one responsibility and one responsibility only if it is displaying information to the userit should not do calculations on the informationif it is handling datait should not concern itself with creating missing pieces on the flyand if it is controlling the flowit should not pay any attention to how data is stored or retrieved or how the data is formatted or displayed parting shots the more cleanly you separate the concerns in your objectsand the better you isolate their purposethe easier it will be to maintain your codeupdate itor find and fix bugs one of the most important concepts you should take with you on your journey toward programming mastery is the paradox of the ship of theseus the paradox is stated as suchimagine you have shipand on the ship they have enough lumber to completely rebuild the ship the ship sets outand along the wayeach piece of lumber built into the ship is replaced by some of the stock carried on the ship the replaced piece is discarded by the time the ship reaches its destinationnot single plank from the original ship remains the question isat what point do you have new shipwhen does the ship cease being the ship you set out withwhat does this have to do with programmingyou should build your programs in such way that you can constantly swap out bits of the program without changing any other part of the code every period--depending on the size and scope of your projectthis might mean year or five years or six months--you want to have cycled out all the old code and replaced it with bettermore elegantand more efficient code keep asking yourself how much of pain it will be to replace the part of the code you are currently working on with something completely different if the answer is that you hope such replacement is not needed before you have moved onrip up the code and start over
8,221
model-view-controller pattern exercises swap out the view from the last implementation of the greeting program to display its output in graphical pop-upyou could look at pygame or pyqt for thisor any other graphics package available to you alter the model to read and write from and to json file rather than flat text file install sqlalchemy and sqlite on your local system and swap out the model object so it uses the database instead of the file system
8,222
publish-subscribe pattern yelling is form of publishing --margaret atwood if you think back to the observer pattern we looked at in you will remember that we had an observable class and some observer classes whenever the observable object changed its state and was polled for changeit alerted all the observers registered with it that they needed to activate callback there is no need to jump back to that as the code we are talking about is in this snippetclass concreteobserver(object)def update(selfobserved)print("observing{}format(observed)class observable(object)def __init__(self)self callbacks set(self changed false def register(selfcallback)self callbacks add(callback(cwessel badenhorst badenhorstpractical python design patterns
8,223
publish-subscribe pattern def unregister(selfcallback)self callbacks discard(callbackdef unregister_all(self)self callbacks set(def poll_for_change(self)if self changedself update_all def update_all(self)for callback in self callbackscallback(selfalthough the observer pattern allows us to decouple the objects that are observed from knowing anything about the objects observing themthe observer objects still need to know which objects they need to observe sowe still have more coupling than we saw in the previous where we were able to change the view code without needing to change the controller or model codeand the same goes for the model code even the controllerwhich sits between the models and the viewsis fairly decoupled from both when we changed the viewwe had no need to also update the controllerand vice versa the observer pattern we dealt with previously works well when number of potential observable classes that an observer needs to register with is limited as with many things in programmingwe are often faced with challenges that do not comply with the ideal caseand so we need to adapt what we are going in search of in this is way to decouple the observer from the observable even more we want neither the observer nor the observable to know anything about each other each class and its instances should be able to change without any changes being needed on the other side of the equation new observers and observables should not require alterations in the code of the other classes in the systemas this would cause our code to be less flexible in an attempt to reach this idealwe will be looking at ways to extend the one-to-many methodologies of the observer pattern to many-to-many relationship between observables and observerssuch that one class of objects does not need to know much about the other these blind observables will be called publishersand the disconnected observers will be named subscribers
8,224
publish-subscribe pattern the first step might seem trivialbut you will soon realize how simple it is to change the way you think about things by just changing what you call them class subscriber(object)def update(selfobserved)print("observing{}format(observed)class publisher(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_all(self)for callback in self callbackscallback(selflike saidthis makes no difference in what the program can actually dobut what it does do is help us see things differently we could now take another step forward and rename the methods in both these classes to reflect the publisher-subscriber model more closely
8,225
publish-subscribe pattern class subscriber(object)def process(selfobserved)print("observing{}format(observed)class publisher(object)def __init__(self)self subscribers set(def subscribe(selfsubscriber)self subscribers add(subscriberdef unsubscribe(selfsubscriber)self subscribers discard(subscriberdef unsubscribe_all(self)self subscribers set(def publish(self)for subscriber in self subscriberssubscriber process(selfnow it is clear that we are dealing with two classesone that deals with publishing and another focused completely on processing something in the code snippetit is not yet clear what should be published and what should be processed we proceed in our attempt to clear up any uncertainty in our model definition by adding message class that could be published and processed class message(object)def __init__(self)self payload none class subscriber(object)def process(selfmessage)print("message{}format(message payload)
8,226
publish-subscribe pattern class publisher(object)def __init__(self)self subscribers set(def subscribe(selfsubscriber)self subscribers add(subscriberdef unsubscribe(selfsubscriber)self subscribers discard(subscriberdef unsubscribe_all(self)self subscribers set(def publish(selfmessage)for subscriber in self subscriberssubscriber process(messagenextwe remove the final link between the publisher and the subscriber by adding single dispatcher class through which all messages will pass the aim is to have single location to which publishers send messages the same location keeps an index of all the subscribers the result is that the number of publishers and subscribers can vary without having any impact on the rest of the system this gives us very clean and decoupled architecture to work with class message(object)def __init__(self)self payload none class subscriber(object)def __init__(selfdispatcher)dispatcher subscribe(selfdef process(selfmessage)print("message{}format(message payload)class publisher(object)def __init__(selfdispatcher)self dispatcher dispatcher
8,227
publish-subscribe pattern def publish(selfmessage)self dispatcher send(messageclass dispatcher(object)def __init__(self)self subscribers set(def subscribe(selfsubscriber)self subscribers add(subscriberdef unsubscribe(selfsubscriber)self subscribers discard(subscriberdef unsubscribe_all(self)self subscribers set(def send(selfmessage)for subscriber in self subscriberssubscriber process(messagenot all subscribers are interested in all the messages from all publishers since the point of this whole exercise was to decouple subscribers from publisherswe do not want to couple them together in any way the solution we are looking for should allow the dispatcher to send categories of messages to specific subscribers we are going to add topic to the messages publishers will now add topic to the messages they publishand subscribers can then subscribe to specific topics class message(object)def __init__(self)self payload none self topic "allclass subscriber(object)def __init__(selfdispatchertopic)dispatcher subscribe(selftopicdef process(selfmessage)print("message{}format(message payload)
8,228
publish-subscribe pattern class publisher(object)def __init__(selfdispatcher)self dispatcher dispatcher def publish(selfmessage)self dispatcher send(messageclass dispatcher(object)def __init__(self)self topic_subscribers dict(def subscribe(selfsubscribertopic)self topic_subscribers setdefault(topicset()add(subscriberdef unsubscribe(selfsubscribertopic)self topic_subscribers setdefault(topicset()discard(subscriberdef unsubscribe_all(selftopic)self subscribers self topic_subscribers[topicset(def send(selfmessage)for subscriber in self topic_subscribers[message topic]subscriber process(messagedef main()dispatcher dispatcher(publisher_ publisher(dispatchersubscriber_ subscriber(dispatcher'topic 'message message(message payload "my payloadmessage topic 'topic publisher_ publish(messageif __name__ ="__main__"main(now we see the code resulting in the message (shown belowprinted by the subscriber messagemy payload
8,229
publish-subscribe pattern distributed message sender sending messages from many machines now that we have arrived at clean implementation of the pubsub patternlet' use the ideas we have developed so far to build our own simple message sender for thiswe are going to use the socket package from the python standard library we use xml-rpc to handle the remote connectionsit lets us make calls to remote procedures as if they were part of the local system in order to make our dispatcher work with messageswe need to send dictionaries as parameters rather than as python objectswhich we do the code below illustrates how we do that dispatcher py from xmlrpc client import serverproxy from xmlrpc server import simplexmlrpcserver class dispatcher(simplexmlrpcserver)def __init__(self)self topic_subscribers dict(super(dispatcherself__init__(("localhost" )print("listening on port "self register_function(self subscribe"subscribe"self register_function(self unsubscribe"unsubscribe"self register_function(self unsubscribe_all"unsubscribe_all"self register_function(self send"send"def subscribe(selfsubscribertopic)print('subscribing {to {}format(subscribertopic)self topic_subscribers setdefault(topicset()add(subscriberreturn "okdef unsubscribe(selfsubscribertopic)print('unsubscribing {from {}format(subscribertopic)self topic_subscribers setdefault(topicset()discard(subscriberreturn "okdef unsubscribe_all(selftopic)print('unsubscribing all from {}format(topic)
8,230
publish-subscribe pattern self subscribers self topic_subscribers[topicset(return "okdef send(selfmessage)print("sending message:\ntopic{}\npayload{}format(message["topic"]message["payload"])for subscriber in self topic_subscribers [message get("topic""all")]with serverproxy(subscriberas subscriber_proxysubscriber_proxy process(messagereturn "okdef main()dispatch_server dispatcher(dispatch_server serve_forever(if __name__ ="__main__"main(publisher py from xmlrpc client import serverproxy class publisher(object)def __init__(selfdispatcher)self dispatcher dispatcher def publish(selfmessage)with serverproxy(self dispatcheras dispatchdispatch send(messagedef main()message {"topic""messagetopic""payload""this is an awesome payload"publisher publisher(publisher publish(messageif __name__ ="__main__"main(
8,231
publish-subscribe pattern subscriber py from xmlrpc client import serverproxy from xmlrpc server import simplexmlrpcserver class subscriber(simplexmlrpcserver)def __init__(selfdispatchertopic)super(subscriberself__init__(("localhost" )print("listening on port "self register_function(self process"process"self subscribe(dispatchertopicdef subscribe(selfdispatchertopic)with serverproxy(dispatcheras dispatchdispatch subscribe(def process(selfmessage)print("message{}format(message get("payload""default message"))return "okdef main()subscriber_server subscriber(subscriber_server serve_forever(if __name__ ="__main__"main(to run the program and see its true effectsyou have to open three terminal windows and activate the virtual environment for your code in each of the windows we will run each part of the application in its own window to simulate the interaction between independent systems each command that follows assumes that the virtualenv is already activated window dispatcher python dispatcher py window subscriber python subscriber py
8,232
publish-subscribe pattern window publisher python publisher py with each of the windows running its processlet' enter message into the publisher window and see what happens we see the dispatcher received the message and sent it to the subscriber listening on port subscribing [ /aug/ : : "post /rpc http/ sending messagetopicmessagetopic payloadthis is an awesome payload [ /aug/ : : "post /rpc http/ the subscriber receives the message and prints the message listening on port messagethis is an awesome payload [ /aug/ : : "post /rpc http/ arting shots the pubsub pattern has many usesespecially as systems expand and grow into the cloud this process of growingexpandingand evolving is one of the reasons chose to start with the simple implementation of the observer pattern we saw in and then move through the steps of improved design to the final full pubsub implementation this is the same pattern of growth that you will repeat in your own projects simple project grows little bitand with every bit of functionality that you addyou should be asking yourself what ideas from this bookor elsewherewill make this project easier to maintain in the future once you hit upon such an ideado not hesitate--improve the code you will quickly come to realize that bit of time spent at the tail end of project will make your development time significantly shorter in future phases of the project
8,233
publish-subscribe pattern as jocko willink (navy seal commander task unit bruserlikes to saydiscipline equals freedom the discipline you apply to your coding practice will lead to freedom from the pain of maintaining cumbersome systems you will also avoid the inevitable dump and rewrite that most software products head for from the moment the first line of code is written exercises see if you can find information about proto buffers and how they could be used to send data to remote procedure calls read up on queueing software like zeromq and rabbitmqtogether with packages like celery implement the simple chat application using one of these instead of the python implementation from this write proposal for how you would use the publish-subscribe pattern to enable the addition of gamification to an existing software as service saas application
8,234
design pattern quick reference quick checks for the code singleton pattern prototype pattern factory pattern builder pattern adapter pattern decorator pattern facade pattern proxy pattern chain of responsibility pattern composite command pattern interpreter pattern iterator pattern observer pattern state pattern strategy pattern (cwessel badenhorst badenhorstpractical python design patterns
8,235
design pattern quick reference template method pattern visitor pattern model-view-controller pattern publisher-subscriber pattern singleton singleton py class singletonobject(object)class __singletonobject()def __init__(self)self val none def __str__(self)return "{ ! { }format(selfself valthe rest of the class definition will follow hereas per the previous logging script instance none def __new__(cls)if not singletonobject instancesingletonobject instance singletonobject __singletonobject(return singletonobject instance def __getattr__(selfname)return getattr(self instancenamedef __setattr__(selfname)return setattr(self instancename
8,236
design pattern quick reference prototype prototype_ py from abc import abcmetaabstractmethod class prototype(metaclass=abcmeta)@abstractmethod def clone(self)pass concrete py from prototype_ import prototype from copy import deepcopy class concrete(prototype)def clone(self)return deepcopy(selffactory factory py import abc class abstractfactory(object)__metaclass__ abc abcmeta @abc abstractmethod def make_object(self)return class concretefactory(abstractfactory)def make_object(self)do something return concreteclass(
8,237
design pattern quick reference builder form_builder py from abc import abcmetaabstractmethod class director(objectmetaclass=abcmeta)def __init__(self)self _builder none @abstractmethod def construct(self)pass def get_constructed_object(self)return self _builder constructed_object class builder(objectmetaclass=abcmeta)def __init__(selfconstructed_object)self constructed_object constructed_object class product(object)def __init__(self)pass def __repr__(self)pass class concretebuilder(builder)pass class concretedirector(director)pass
8,238
design pattern quick reference adapter third_party py class whatihave(object)def provided_function_ (self)pass def provided_function_ (self)pass class whatiwant(object)def required_function()pass adapter py from third_party import whatihave class objectadapter(object)def __init__(selfwhat_i_have)self what_i_have what_i_have def required_function(self)return self what_i_have provided_function_ (def __getattr__(selfattr)everything else is handled by the wrapped object return getattr(self what_i_haveattrdecorator decorator py from functools import wraps def dummy_decorator( )@wraps(fdef wrap_f()print("function to be decorated" __name__print("nested wrapping function"wrap_f __name__return (return wrap_f
8,239
design pattern quick reference @dummy_decorator def do_nothing()print("inside do_nothing"if __name__ ="__main__"print("wrapped function",do_nothing __name__do_nothing(facade simple_ facade py class invoicedef __init__(selfcustomer)pass class customeraltered customer class to try to fetch customer on init or creates new one def __init__(selfcustomer_id)pass class itemaltered item class to try to fetch an item on init or creates new one def __init__(selfitem_barcode)pass class facade@staticmethod def make_invoice(customer)return invoice(customer@staticmethod def make_customer(customer_id)return customer(customer_id@staticmethod def make_item(item_barcode)return item(item_barcode
8,240
design pattern quick reference proxy proxy py import time class rawclass(object)def func(selfn)return (ndef memoize(fn)__cache {def memoized(*args)key (fn __name__argsif key in __cachereturn __cache[key__cache[keyfn(*argsreturn __cache[keyreturn memoized class classproxy(object)def __init__(selftarget)self target target func getattr(self target'func'setattr(self target'func'memoize(func)def __getattr__(selfname)return getattr(self targetname
8,241
design pattern quick reference chain of responsibility chain_of_responsibility py class endhandler(object)def __init__(self)pass def handle_request(selfrequest)pass class handler (object)def __init__(self)self next_handler endhandler(def handle_request(selfrequest)self next_handler handle_request(requestdef main(request)concrete_handler handler (concrete_handler handle_request(requestif __name__ ="__main__"from the command line we can define some request main(requestalternative chain_of_responsibility_alt py class dispatcher(object)def __init__(selfhandlers=[])self handlers handlers def handle_request(selfrequest)for handler in self handlersrequest handler(requestreturn request
8,242
design pattern quick reference command command py class commanddef __init__(selfreceivertext)self receiver receiver self text text def execute(self)self receiver print_message(self textclass receiver(object)def print_message(selftext)print("message received{}format(text)class invoker(object)def __init__(self)self commands [def add_command(selfcommand)self commands append(commanddef run(self)for command in self commandscommand execute(if __name__ ="__main__"receiver receiver(command command(receiver"execute command "command command(receiver"execute command "invoker invoker(invoker add_command(command invoker add_command(command invoker run(
8,243
design pattern quick reference composite composite py class leaf(object)def __init__(self*args**kwargs)pass def component_function(self)print("leaf"class composite(object)def __init__(self*args**kwargs)self children [def component_function(self)for child in childrenchild component_function(def add(selfchild)self children append(childdef remove(selfchild)self children remove(childinterpreter interpreter py class nonterminal(object)def __init__(selfexpression)self expression expression def interpret(self)self expression interpret(class terminal(object)def interpret(self)pass
8,244
design pattern quick reference iterator classic_iterator py import abc class iterator(metaclass=abc abcmeta)@abc abstractmethod def has_next(self)pass @abc abstractmethod def next(self)pass class container(metaclass=abc abcmeta)@abc abstractmethod def getiterator(self)pass class mylistiterator(iterator)def __init__(selfmy_list)self index self list my_list list def has_next(self)return self index len(self listdef next(self)self index + return self list[self index class mylist(container)def __init__(self*args)self list list(argsdef getiterator(self)return mylistiterator(self
8,245
design pattern quick reference if __name__ ="__main__"my_list mylist( my_iterator my_list getiterator(while my_iterator has_next()print(my_iterator next()alternative iterator_alt py for element in collectiondo_something(elementobserver observer py class concreteobserver(object)def update(selfobserved)print("observing{}format(observed)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(
8,246
design pattern quick reference def poll_for_change(self)if self changedself update_all def update_all(self)for callback in self callbackscallback(selfstate state py class state(object)pass class concretestate (state)def __init__(selfstate_machine)self state_machine state_machine def switch_state(self)self state_machine state self state_machine state class concretestate (state)def __init__(selfstate_machine)self state_machine state_machine 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(
8,247
design pattern quick reference def __str__(self)return str(self statedef main()state_machine statemachine(print(state_machinestate_machine switch(print(state_machineif __name__ ="__main__"main(strategy strategy py def executor(arg arg func=none)if func is nonereturn "strategy not implemented return func(arg arg def strategy_ (arg arg )return f_ (arg arg def strategy_ (arg arg )return f_ (arg arg template method template_method py import abc class templateabstractbaseclass(metaclass=abc abcmeta)def template_method(self)self _step_ (self _step_ (self _step_n(
8,248
design pattern quick reference @abc abstractmethod def _step_ (self)pass @abc abstractmethod def _step_ (self)pass @abc abstractmethod def _step_ (self)pass class concreteimplementationclass(templateabstractbaseclass)def _step_ (self)pass def _step_ (self)pass def _step_ (self)pass visitor visitor py import abc 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(self
8,249
design pattern quick reference class abstractvisitor(object)__metaclass__ abc abcmeta @abc abstractmethod def visit(selfelement)raise notimplementederror(" visitor need to define visit method"class concretevisitable(visitable)def __init__(self)pass class concretevisitor(abstractvisitor)def visit(selfelement)pass model-view-controller mvc py import sys class genericcontroller(object)def __init__(self)self model genericmodel(self view genericview(def handle(selfrequest)data self model get_data(requestself view generate_response(dataclass genericmodel(object)def __init__(self)pass def get_data(selfrequest)return {'request'request
8,250
design pattern quick reference class genericview(object)def __init__(self)pass def generate_response(selfdata)print(datadef main(name)request_handler genericcontroller(request_handler handle(nameif __name__ ="__main__"main(sys argv[ ]publisher-subscriber publish_subscribe py class message(object)def __init__(self)self payload none self topic "allclass subscriber(object)def __init__(selfdispatchertopic)dispatcher subscribe(selftopicdef process(selfmessage)print("message{}format(message payload)class publisher(object)def __init__(selfdispatcher)self dispatcher dispatcher def publish(selfmessage)self dispatcher send(message
8,251
design pattern quick reference class dispatcher(object)def __init__(self)self topic_subscribers dict(def subscribe(selfsubscribertopic)self topic_subscribers setdefault(topicset()add(subscriberdef unsubscribe(selfsubscribertopic)self topic_subscribers setdefault(topicset()discard(subscriberdef unsubscribe_all(selftopic)self subscribers self topic_subscribers[topicset(def send(selfmessage)for subscriber in self topic_subscribers[message topic]subscriber process(messagefinal words well doneyou have learned many useful patterns hope that you will continue to practice and become better programmer every day thank you for going on this journey with me goodbye and good luck
8,252
abstract base class (abc) adapter pattern class adapter don' repeat yourself duck typing implementation mail_sender py object parting shots problem send_email py separation of concern users csv file barracks builder pattern abstraction anti-patterns basic_form_generator py cleaned_html_dictionary_form_ generator py course correct deliberate practice focus giants graphical library/machine-learning setup html_dictionary_form_generator py html_form_generator py - oop_html_form_generator py rapid feedback loop vincileonardo da widgets and interfaces chain of responsibility pattern authentication headers response object functions - implementation middleware print function - python (see pythonic implementationsingle responsibility principle wsgi server clone(method closures command pattern commands execute(method function definition implementation invoker macros multi-level undo stack multiplication receiver relevant parameters turtle composite pattern (cwessel badenhorst badenhorstpractical python design patterns
8,253
table of contents about the tutorial audience prerequisites copyright disclaimer table of contents ii python design patterns introduction structure of design pattern why python python design patterns gist of python features of python language important points how to download python language in your system the important tools in python what constitutes design pattern in python python design patterns model view controller pattern python design patterns singleton pattern how to implement singleton class python design patterns factory pattern how to implement factory pattern python design patterns builder pattern how to implement builder pattern python design patterns prototype pattern how to implement prototype pattern python design patterns facade pattern how to design facade pattern python design patterns command pattern ii
8,254
how to implement the command pattern python design patterns adapter pattern how to implement the adapter pattern python design patterns decorator pattern how to implement decorator design pattern python design patterns proxy pattern how to implement the proxy pattern python design patterns chain of responsibility pattern how to implement the chain of responsibility pattern python design patterns observer pattern how to implement the observer pattern python design patterns state pattern how to implement the state pattern python design patterns strategy pattern how to implement the strategy pattern python design patterns template pattern python design patterns flyweight pattern how to implement the flyweight pattern python design patterns abstract factory pattern how to implement the abstract factory pattern python design patterns object oriented pattern how to implement the object oriented pattern python design patterns object oriented concepts implementation how to implement classes and object variables python design patterns iterator pattern how to implement the iterator pattern python data structure dictionaries how to implement dictionaries in python iii
8,255
python design pattern the lists data structure how to implement lists python design patterns sets how to implement sets python design patterns queues how to implement the fifo procedure how to implement the lifo procedure what is priority queue python design patterns strings and serialization python design patterns concurrency in python python design patterns anti-patterns important features of anti-patterns python design patterns exception handling why use exceptions iv
8,256
python design patterns introduction design patterns are used to represent the pattern used by developers to create software or web application these patterns are selected based on the requirement analysis the patterns describe the solution to the problemwhen and where to apply the solution and the consequences of the implementation structure of design pattern the documentation of design pattern is maintained in way that focuses more on the technology that is used and in what ways the following diagram explains the basic structure of design pattern documentation pattern name it describes the pattern in short and effective manner intent/motive it describes what the pattern does applicability it describes the list of situations where pattern is applicable
8,257
participants and consequences participants include classes and objects that participate in the design pattern with list of consequences that exist with the pattern why pythonpython is an open source scripting language it has libraries that support variety of design patterns the syntax of python is easy to understand and uses english keywords python provides support for the list of design patterns that are mentioned below these design patterns will be used throughout this tutorialmodel view controller pattern singleton pattern factory pattern builder pattern prototype pattern facade pattern command pattern adapter pattern prototype pattern decorator pattern proxy pattern chain of responsibility pattern observer pattern state pattern strategy pattern template pattern flyweight pattern abstract factory pattern object oriented pattern benefits of using design pattern following are the different benefits of design patternpatterns provide developer selection of tried and tested solutions for the specified problems all design patterns are language neutral
8,258
patterns help to achieve communication and maintain well documentation it includes record of accomplishment to reduce any technical risk to the project design patterns are highly flexible to use and easy to understand
8,259
python design patterns gist ofpython python python is an open source scripting languagewhich is high-levelinterpretedinteractive and object-oriented it is designed to be highly readable the syntax of python language is easy to understand and uses english keywords frequently features of python language in this sectionwe will learn about the different features of python language interpreted python is processed at runtime using the interpreter there is no need to compile program before execution it is similar to perl and php object-oriented python follows object-oriented style and design patterns it includes class definition with various features like encapsulationpolymorphism and many more portable python code written in windows operating system and can be used in mac operating system the code can be reused and portable as per the requirements easy to code python syntax is easy to understand and code any developer can understand the syntax of python within few hours python can be described as "programmer-friendlyextensible if neededa user can write some of python code in language as well it is also possible to put python code in source code in different languages like +this makes python an extensible language important points consider the following important points related to python programming languageit includes functional and structured programming methods as well as objectoriented programming methods it can be used as scripting language or as programming language it includes automatic garbage collection
8,260
it includes high-level dynamic data types and supports various dynamic type checking python includes feature of integration with cc+and languages like java
8,261
how to download python language in your systemto download python language in your systemfollow this linkit includes packages for various operating systems like windowsmacos and linux distributions the important tools in python in this sectionwe will learn in brief about few important tools in python python strings the basic declaration of strings is as followsstr 'hello world!python lists the lists of python can be declared as compound data types separated by commas and enclosed within square brackets ([]list 'abcd' 'john' tinylist [ 'john'python tuples tuple is dynamic data type of pythonwhich consists of number of values separated by commas tuples are enclosed with parentheses tinytuple ( 'john'
8,262
python dictionary python dictionary is type of hash table dictionary key can be almost any data type of python the data types are usually numbers or strings tinydict {'name''omkar','code': 'dept''sales'what constitutes design pattern in pythonpython helps in constituting design pattern using the following parameterspattern name intent aliases motivation problem solution structure participants constraints sample code
8,263
python design patterns model view controller pattern model view controller is the most commonly used design pattern developers find it easy to implement this design pattern following is basic architecture of the model view controllerlet us now see how the structure works model it consists of pure application logicwhich interacts with the database it includes all the information to represent data to the end user view
8,264
view represents the html fileswhich interact with the end user it represents the model' data to user controller it acts as an intermediary between view and model it listens to the events triggered by view and queries model for the same python code let us consider basic object called "personand create an mvc design pattern model py import json class person(object)def __init__(selffirst_name nonelast_name none)self first_name first_name self last_name last_name #returns person nameexjohn doe def name(self)return ("% % (self first_name,self last_name)@classmethod #returns all people inside db txt as list of person objects def getall(self)database open('db txt'' 'result [json_list json loads(database read()for item in json_listitem json loads(itemperson person(item['first_name']item['last_name']result append(personreturn result it calls for methodwhich fetches all the records of the person table in database the records are presented in json format
8,265
view it displays all the records fetched within the model view never interacts with modelcontroller does this work (communicating with model and viewfrom model import person def showallview(list)print 'in our db we have % users here they are:len(listfor item in listprint item name(def startview()print 'mvc the simplest exampleprint 'do you want to see everyone in my db?[ / ]def endview()print 'goodbye!controller controller interacts with model through the getall(method which fetches all the records displayed to the end user from model import person import view def showall()#gets list of all person objects people_in_db person getall(#calls view return view showallview(people_in_dbdef start()view startview(input raw_input(if input =' 'return showall(else
8,266
return view endview(if __name__ ="__main__"#running controller function start(
8,267
python design patterns singleton pattern this pattern restricts the instantiation of class to one object it is type of creational pattern and involves only one class to create methods and specified objects it provides global point of access to the instance created how to implement singleton classthe following program demonstrates the implementation of singleton class where it prints the instances created multiple times class singleton__instance none @staticmethod def getinstance()""static access method ""if singleton __instance =nonesingleton(
8,268
return singleton __instance def __init__(self)""virtually private constructor ""if singleton __instance !noneraise exception("this class is singleton!"elsesingleton __instance self singleton(print singleton getinstance(print singleton getinstance(print output the above program generates the following output
8,269
the number of instances created are same and there is no difference in the objects listed in output
8,270
python design patterns factorypython pattern the factory pattern comes under the creational patterns list category it provides one of the best ways to create an object in factory patternobjects are created without exposing the logic to client and referring to the newly created object using common interface factory patterns are implemented in python using factory method when user calls method such that we pass in string and the return value as new object is implemented through factory method the type of object used in factory method is determined by string which is passed through method in the example belowevery method includes object as parameterwhich is implemented through factory method how to implement factory patternlet us now see how to implement factory pattern class button(object)html "def get_html(self)return self html class image(button)html "class input(button)html "class flash(button)html "class buttonfactory()def create_button(selftyp)targetclass typ capitalize(return globals()[targetclass](button_obj buttonfactory(
8,271
"forces"some richcomplex subsystem offers lot of useful functionalityclient code interacts with several parts of this functionality in way that' "out of controlthis causes many problems for client-code programmers and subsystem ones too (complexity rigidity
8,272
interpose simpler "facadeobject/class exposing controlled subset of functionality dp "facadeclient code now calls existing supplier code provides ric into the facadeonly complex functionality in protocol the facade implements we need simpler "subsetc of facade code implements and supp its simpler functionality (by calling on !via calls into the richcomplex subsystem subsystem implementation gains flexibilityclients gain simplicity ( ab strakt
8,273
summary of frequent design problem structure of solution to that problem (pros and consalternatives)anda name (much easier to retain/discuss!"descriptions of communicating objects and classes customized to solve general design problem in particular contextthat' nota data structurealgorithmdomain-specific system architectureprogramming-language/library feature must be studied in language' contextmust supply known uses ("ku"
8,274
in the python standard library dbhash facades for bsddb highly simplified/subset access also meets the "dbminterface (thusalso an example of the adapter dpos pathbasenamedirname facade for split indexingisdir (&cfacade for os stat stat s_isdir (&cfacade is structural dp (we'll see anotheradapterlaterin dbhashthey "merge"!-
8,275
8,276
summary of frequent design problem structure of solution to that problem pros and consalternativesanda name (much easier to retain/discuss!"descriptions of communicating objects and classes customized to solve general design problem in particular contextdps are notdata structuresalgorithmsdomain-specific system architecturesprogramming language features must be studied in language' contextmust supply known uses ("ku"
8,277
(biblio on the last slide
8,278
creationalways and means of object instantiation structuralmutual composition of classes or objects (the facade dp is structuralbehavioralhow classes or objects interact and distribute responsibilities among them each can be class-level or object-level
8,279
"program to an interfacenot to an implementationthat' mostly done with "duck typingin python -rarely /"formalinterfaces actually similar to "signature-based polymorphismin +templates
8,280
teaching the ducks to type takes whilebut saves you lot of work afterwards!-
8,281
"favor object composition over class inheritancein pythonholdor wrap inherit only when it' really convenient expose all methods in base class (reuse usually override maybe extendbutit' very strong coupling
8,282
8,283
"hold"object has subobject as an attribute (maybe property-that' all use self method or method simpledirectimmediatebut pretty strong couplingoften on the wrong axis holder holdee client
8,284
"wrap"hold (often via private nameplus delegation (so you directly use methodexplicit (def method(self self methodautomatic (delegation in __getattr__gets coupling right (law of demeterwrapper wrappee client
8,285
class restrictingwrapper(object)def __init__(selfwblock)self _w self _block block def __getattr__(selfn)if in self _blockraise attributeerrorn return getattr(self _wninheritance cannot restrict
8,286
not very common in python because "factoryis essentially built-in!-
8,287
"we want just one instance to existuse module instead of class no subclassingno special methodsmake just instance (no enforcementneed to commit to "whento make it singleton ("highlander"subclassing not really smooth monostate ("borg"guido dislikes it
8,288
class singleton(object)def __new__(cls* ** )if not hasattr(cls'_inst')cls _inst super(singletoncls __new__(cls* **kreturn cls _inst subclassing is problemthoughclass foo(singleton)pass class bar(foo)pass foo() bar()??problem is intrinsic to singleton
8,289
class borg(object)_shared_state {def __new__(cls* ** )obj super(borgcls __new__(cls* **kobj __dict__ cls _shared_state return obj subclassing is no problemjustclass foo(borg)pass class bar(foo)pass class baz(foo)_shared_state {data overriding to the rescue
8,290
"we don' want to commit to instantiating specific concrete class"dependency injectiondp no creation except "outsidewhat if multiple creations are needed"factorysubcategory of dps may create /ever or reuse existing factory functions (other callablesfactory methods (overridableabstract factory classes
8,291
"masquerading/adaptationsubcategoryadaptertweak an interface (both class and object variants existfacadesimplify subsystem' interface and many others don' coversuch asbridgemany implementations of an abstractionmany implementations of functionalityno repetitive coding decoratorreuse+tweak / inheritance proxydecouple from access/location
8,292
client code requires protocol supplier code provides different protocol (with superset of ' functionalityadapter code "sneaks in the middle"to ga is supplier (produces protocol cto sa is client (consumes protocol "inside" implements (by means of appropriate calls to on
8,293
requires method foobar(foobars supplies method barfoo(barfooe could beclass barfooer(object)def barfoo(selfbarfoo)
8,294
per-instancewith wrapping delegationclass foobarwrapper(object)def __init__(selfwrappee)self wrappee def foobar(selffoobar)return self barfoo(barfoofoobarer=foobarwrapper(barfooer
8,295
per-classw/subclasing self-delegationclass foobarer(barfooer)def foobar(selffoobar)return self barfoo(barfoofoobarer=foobarerw/ever
8,296
flexiblegood use of multiple inheritanceclass bf fbdef foobar(selffoobar)return self barfoo(barfooclass foobarer(bf fbbarfooer)pass foobarer=foobarerw/ever
8,297
socket _fileobjectfrom sockets to file-like objects ( /much code for bufferingdoctest doctestsuiteadapts doctest tests to unittest testsuite dbhashadapt bsddb to dbm stringioadapt str or unicode to file-like shelveadapt "limited dict(str keys and valuesbasic methodsto complete mapping via pickle for any string userdict dictmixin
8,298
some rl adapters may require much code mixin classes are great way to help adapt to rich protocols (implement advanced methods on top of fundamental onesadapter occurs at all levels of complexity in pythonit' _not_ just about classes and their instances (by long shot!--often _callables_ are adapted (via decorators and other hofsclosuresfunctools
8,299
adapter' about supplying given protocol required by client-code orgain polymorphism via homogeneity facade is about simplifying rich interface when just subset is often needed facade most often "frontsfor subsystem made up of many classes/objectsadapter "frontfor just one single object or class