Workshop 03 - Design Patterns Basics← Home → |
|
|
Singleton (Creational Design Pattern)Consider the case of one class having a single private constructor. Apparently, it is impossible or, at least, useless.Analyze the below Singleton thread safe implementation: Generic singleton implementation: Proxy (Structural Design Pattern)Multiple inheritance is not allowed in .Net. However, when necessary, it could be simulated using the Proxy patternStrategy (Behavioral Design Pattern)Allows selecting an algorithm at runtime.Factory (Creational Design Pattern)The Strategy pattern is often used in combination with Factory.Side note - RecursionConsider the Manna-Pnueli function:
1) Calculate f(8); 2) Implement an iterative solution. f(8) = f(f(10)) = f(f(f(12))) = f(f(11)) = f(f(f(13))) = f(f(12)) = f(11) = f(f(13)) = f(12) = 11 Let's write the same thing... vertically. The "floor" corresponds to the number of "f"-s:
One can notice only 2 variables are necessary: the current value, and the number of calls (the number of "f"-s). The algorithm ends when the "floor" becomes 0. The Manna-Pnueli recursive solution is immediate: just "copy" the function definition... Observation! Although it is sometimes easier to implement, the recursive method could be less efficient than the iterative one. - For example, in the Manna-Pnueli case, only 2 variables are necessary in the iterative approach (instead of a stack). - Fibonacci series is an example of highly unrecommended, CASCADE RECURSION, when implemented by directly employing the recurrent expression: Fib(n) = Fib(n-2) + Fib(n-1)
Consider below, a correct Fibonacci recursive implementation at O(n)! One should also pay an important attention to indirect recursion [f() calls g() - g() calls f()], as it could result in unwanted "stack overflow exceptions": Template Method (Behavioral Design Pattern)Consider the below Template design pattern used for implementing the Backtracking programming technique:Inherit the previous abstract class for implementing various problems: generating permutations, cartesian product, etc.
References:Design Patterns |
|
← Home → |