about summary refs log tree commit diff
path: root/usth/ICT2.7/P3L3 Design Patterns Subtitles/12 - Choosing a Pattern Quiz Solution - lang_en_vs4.srt
blob: c348a2ca1f8670ad158b625d0784a6f066e16468 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
1
00:00:00,220 --> 00:00:01,750
As we discussed in the class the right thing to

2
00:00:01,750 --> 00:00:05,050
do here was to use the factory pattern. So here is

3
00:00:05,050 --> 00:00:07,910
a possible code to solve the problem. Of course that there

4
00:00:07,910 --> 00:00:11,220
are different possible solutions. So what we did for this code

5
00:00:11,220 --> 00:00:16,210
was to first create a private, static, Singleton object called

6
00:00:16,210 --> 00:00:19,340
instance, which is the one that will keep track of the

7
00:00:19,340 --> 00:00:22,250
only instance that can be created on the class. Then we

8
00:00:22,250 --> 00:00:25,750
define the default constructor, the constructor that doesn't take any parameter

9
00:00:25,750 --> 00:00:29,900
as private. In this way other classes cannot create instances

10
00:00:29,900 --> 00:00:33,310
of Singleton without calling our factory method, and finally we

11
00:00:33,310 --> 00:00:35,650
create the factory method. And the factory method is very

12
00:00:35,650 --> 00:00:38,600
simple. The method will first check whether an instance of

13
00:00:38,600 --> 00:00:40,970
the class was already created. If it was created, it

14
00:00:40,970 --> 00:00:44,010
would just return that instance. Otherwise, it will create a

15
00:00:44,010 --> 00:00:47,550
new instance and assign it to that instance member variable

16
00:00:47,550 --> 00:00:50,960
and then return the newly created instance. So with this code

17
00:00:50,960 --> 00:00:53,540
you're guaranteed that other classes cannot bypass the factory

18
00:00:53,540 --> 00:00:56,530
method, because the default constructor is private. And the that

19
00:00:56,530 --> 00:00:59,600
the factory method will create one and only one instance

20
00:00:59,600 --> 00:01:02,020
of the class, which is exactly what our requirements were.