12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Why Factories?So what good is the factory function (besides providing an excuse to illustrate classobjects in this book)? Unfortunately, it’s difficult to show applications of this designpattern without listing much more code than we have space for here. In general,though, such a factory might allow code to be insulated from the details of dynamicallyconfigured object construction.For example, recall the processor example presented in the abstract in Chapter 22,and then again as a has-a composition example in this chapter. It accepted readerand writer objects for processing arbitrary data streams.The original version of this example manually passed in instances of specializedclasses like FileWriter and SocketReader to customize the data streams being processed;later, we passed in hardcoded file, stream, and formatter objects. In a moredynamic scenario, external devices such as configuration files or GU<strong>Is</strong> might be usedto configure the streams.In such a dynamic world, we might not be able to hardcode the creation of streaminterface objects in our script, but might instead create them at runtime according tothe contents of a configuration file.For instance, the file might simply give the string name of a stream class to beimported from a module, plus an optional constructor call argument. Factory-stylefunctions or code might come in handy here because they would allow us to fetchand pass in classes that are not hardcoded in our program ahead of time. Indeed,those classes might not even have existed at all when we wrote our code:classname = ...parse from config file...classarg = ...parse from config file...import streamtypesaclass = getattr(streamtypes, classname)reader = factory(aclass, classarg)processor(reader, ...)# Customizable code# Fetch from module# Or aclass(classarg)Here, the getattr built-in is again used to fetch a module attribute given a stringname (it’s like saying obj.attr, but attr is a string). Because this code snippetassumes a single constructor argument, it doesn’t strictly need factory or apply—wecould make an instance with just aclass(classarg). They may prove more useful inthe presence of unknown argument lists, however, and the general factory codingpattern can improve the code’s flexibility. For more details on this topic, please consultbooks that cover OOP design and design patterns.Classes Are Objects: Generic Object Factories | 533

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!