You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Design_Patterns_In_Python.tex
+14-2Lines changed: 14 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -180,8 +180,19 @@ \section{Singleton}
180
180
181
181
This is certainly the most controversial pattern on this list.
182
182
183
-
This is another easy pattern to implement in Python. In C++ you have to make the constructors
184
-
183
+
In C++ you have to ensure that a new instance of the singleton cannot be made. This is typically done by protecting the constructors and making a static Instance() function which returns the current instance, or makes a new one if it is appropriate.
184
+
185
+
This is another easy pattern to implement in Python. It is a case of overriding the \_\_new()\_\_ function. This is a static method for all classes which is called on construction. This function is called with an argument of the class type requested and returns a new instance of that class. So to implement the singleton pattern it is a case of making sure that the \_\_new()\_\_ method returns the global instance. This can be done with the following code:
186
+
\begin{lstlisting}
187
+
def __new__(new_singleton):
188
+
"""Override the __new__ method so that it is a singleton."""
print("An actual new instance of Singleton made.")
192
+
print("")
193
+
return new_singleton.instance
194
+
\end{lstlisting}
195
+
Here the class name is Singleton and instance is a member variable initialised to None.
185
196
186
197
\chapter{Structural}
187
198
@@ -231,6 +242,7 @@ \section{Interpreter}
231
242
\section{Iterator}
232
243
% table of information for the start of a section
233
244
\patternSummaryGoalMotProCon{}{}{}{}
245
+
This is a pattern which falls into the catagory of included in Python already. This is because anything which can be iterated over is able to be. This goes for built in classes but if you want to make an iterable class you need to supply two methods; \_\_iter\_\_() and next().
0 commit comments