1 from abc import ABCMeta, abstractmethod
2
3
4 -class Director(object, metaclass=ABCMeta):
5 """
6 Abstract director class, responsible for using a builder to fully construct an object.
7
8 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Creational-Pattern-Usage}
9 - External Builder Pattern documentation: U{https://en.wikipedia.org/wiki/Builder_pattern}
10 """
11
13 """
14 Initialize a new Director.
15 """
16 self.builder = None
17
18 @abstractmethod
20 """
21 Abstract method for fully constructing an object.
22
23 Concrete implementations should override this and use a builder to construct the object.
24
25 @raise NotImplementedError: If this method is not overridden.
26 """
27 pass
28
30 """
31 Get the object this director is responsible for constructing.
32
33 @return: The object that this director is responsible for constructing.
34 """
35 return self.builder.constructed_object
36
37
38 -class Builder(object, metaclass=ABCMeta):
39 """
40 Abstract builder class, responsible for constructing various pieces of an object.
41
42 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Creational-Pattern-Usage}
43 - External Builder Pattern documentation: U{https://en.wikipedia.org/wiki/Builder_pattern}
44 """
45
47 """
48 Initialize a new Builder.
49
50 Concrete Builders should call this method from within their own __init__ method.
51 The concrete __init__ method should also register all build options to build methods,
52 by using the _register method.
53
54 @param constructed_object: An instance of an object this builder is responsible for.
55 """
56 self.constructed_object = constructed_object
57 self.build_methods = dict()
58
59 - def build(self, build_option, **kwargs):
60 """
61 Build a piece of the constructed object.
62
63 @param build_option: The part of the object to build. All build options should have been registered in __init__.
64 @type build_option: str
65 @param kwargs: Additional arguments for building.
66 """
67 self.build_methods[build_option](**kwargs)
68
69 - def _register(self, build_option, build_method):
70 """
71 Register a build option to a build method.
72
73 All concrete builders should call this method in their constructor at least once.
74
75 @param build_option: A string representing the part of the object to build.
76 @type build_option: str
77 @param build_method: The method to call when given build option is selected.
78 """
79 self.build_methods[build_option] = build_method
80