-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03-template-method-pattern.py
More file actions
543 lines (395 loc) · 16.6 KB
/
03-template-method-pattern.py
File metadata and controls
543 lines (395 loc) · 16.6 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
"""Question: Implement the Template Method pattern using abstract classes.
Create an abstract DataProcessor class with a template method process_data() that defines
the algorithm steps. Implement concrete subclasses CSVProcessor and JSONProcessor.
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about what classes and methods you need
# - Start with a simple implementation
# - Test your code step by step
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - What is the Template Method pattern?
# - How do you define a template method that calls abstract methods?
# - What steps might be common to all data processors?
# - How do concrete classes customize specific steps?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Create the abstract DataProcessor class
# ===============================================================================
# Explanation:
# The Template Method pattern defines the skeleton of an algorithm in a base class,
# letting subclasses override specific steps without changing the algorithm structure.
from abc import ABC, abstractmethod
class DataProcessor(ABC):
def process_data(self, source, destination):
"""Template method that defines the data processing algorithm"""
print(f"Starting data processing from {source} to {destination}")
# Step 1: Load data
data = self.load_data(source)
# Step 2: Validate data
if self.validate_data(data):
# Step 3: Transform data
transformed_data = self.transform_data(data)
# Step 4: Save data
self.save_data(transformed_data, destination)
print("Data processing completed successfully")
else:
print("Data validation failed")
# What we accomplished in this step:
# - Created the abstract base class with template method
# - Defined the algorithm structure in process_data()
# Step 2: Add abstract methods for customization points
# ===============================================================================
# Explanation:
# Abstract methods define the steps that subclasses must implement.
# These are the customization points in our template method.
from abc import ABC, abstractmethod
class DataProcessor(ABC):
def process_data(self, source, destination):
"""Template method that defines the data processing algorithm"""
print(f"Starting data processing from {source} to {destination}")
# Step 1: Load data
data = self.load_data(source)
# Step 2: Validate data
if self.validate_data(data):
# Step 3: Transform data
transformed_data = self.transform_data(data)
# Step 4: Save data
self.save_data(transformed_data, destination)
print("Data processing completed successfully")
else:
print("Data validation failed")
@abstractmethod
def load_data(self, source):
"""Load data from source - must be implemented by subclasses"""
pass
@abstractmethod
def validate_data(self, data):
"""Validate loaded data - must be implemented by subclasses"""
pass
@abstractmethod
def transform_data(self, data):
"""Transform data - must be implemented by subclasses"""
pass
@abstractmethod
def save_data(self, data, destination):
"""Save data to destination - must be implemented by subclasses"""
pass
# What we accomplished in this step:
# - Added abstract methods for each customization point
# - Defined the contract that subclasses must follow
# Step 3: Implement CSVProcessor
# ===============================================================================
# Explanation:
# The CSVProcessor implements all abstract methods with CSV-specific logic.
# It inherits the template method but customizes the individual steps.
from abc import ABC, abstractmethod
class DataProcessor(ABC):
def process_data(self, source, destination):
"""Template method that defines the data processing algorithm"""
print(f"Starting data processing from {source} to {destination}")
# Step 1: Load data
data = self.load_data(source)
# Step 2: Validate data
if self.validate_data(data):
# Step 3: Transform data
transformed_data = self.transform_data(data)
# Step 4: Save data
self.save_data(transformed_data, destination)
print("Data processing completed successfully")
else:
print("Data validation failed")
@abstractmethod
def load_data(self, source):
"""Load data from source - must be implemented by subclasses"""
pass
@abstractmethod
def validate_data(self, data):
"""Validate loaded data - must be implemented by subclasses"""
pass
@abstractmethod
def transform_data(self, data):
"""Transform data - must be implemented by subclasses"""
pass
@abstractmethod
def save_data(self, data, destination):
"""Save data to destination - must be implemented by subclasses"""
pass
class CSVProcessor(DataProcessor):
def load_data(self, source):
print(f"📄 Loading CSV data from {source}")
# Simulate CSV loading
return [
["Name", "Age", "City"],
["Alice", "25", "New York"],
["Bob", "30", "San Francisco"],
["Charlie", "35", "Chicago"]
]
def validate_data(self, data):
print("✅ Validating CSV data structure")
# Check if we have headers and data rows
if len(data) < 2:
return False
# Check if all rows have same number of columns
header_length = len(data[0])
return all(len(row) == header_length for row in data)
def transform_data(self, data):
print("🔄 Transforming CSV data (converting to uppercase)")
# Convert all text to uppercase except headers
transformed = [data[0]] # Keep headers as-is
for row in data[1:]:
transformed.append([cell.upper() if isinstance(cell, str) else cell for cell in row])
return transformed
def save_data(self, data, destination):
print(f"💾 Saving CSV data to {destination}")
# Simulate saving CSV
for row in data:
print(f" {','.join(row)}")
# What we accomplished in this step:
# - Implemented CSVProcessor with CSV-specific logic
# - Each method handles CSV format appropriately
# Step 4: Implement JSONProcessor
# ===============================================================================
# Explanation:
# The JSONProcessor shows how the same template method can work with
# completely different data formats and processing logic.
from abc import ABC, abstractmethod
import json
class DataProcessor(ABC):
def process_data(self, source, destination):
"""Template method that defines the data processing algorithm"""
print(f"Starting data processing from {source} to {destination}")
# Step 1: Load data
data = self.load_data(source)
# Step 2: Validate data
if self.validate_data(data):
# Step 3: Transform data
transformed_data = self.transform_data(data)
# Step 4: Save data
self.save_data(transformed_data, destination)
print("Data processing completed successfully")
else:
print("Data validation failed")
@abstractmethod
def load_data(self, source):
"""Load data from source - must be implemented by subclasses"""
pass
@abstractmethod
def validate_data(self, data):
"""Validate loaded data - must be implemented by subclasses"""
pass
@abstractmethod
def transform_data(self, data):
"""Transform data - must be implemented by subclasses"""
pass
@abstractmethod
def save_data(self, data, destination):
"""Save data to destination - must be implemented by subclasses"""
pass
class CSVProcessor(DataProcessor):
def load_data(self, source):
print(f"📄 Loading CSV data from {source}")
return [
["Name", "Age", "City"],
["Alice", "25", "New York"],
["Bob", "30", "San Francisco"],
["Charlie", "35", "Chicago"]
]
def validate_data(self, data):
print("✅ Validating CSV data structure")
if len(data) < 2:
return False
header_length = len(data[0])
return all(len(row) == header_length for row in data)
def transform_data(self, data):
print("🔄 Transforming CSV data (converting to uppercase)")
transformed = [data[0]]
for row in data[1:]:
transformed.append([cell.upper() if isinstance(cell, str) else cell for cell in row])
return transformed
def save_data(self, data, destination):
print(f"💾 Saving CSV data to {destination}")
for row in data:
print(f" {','.join(row)}")
class JSONProcessor(DataProcessor):
def load_data(self, source):
print(f"📋 Loading JSON data from {source}")
# Simulate JSON loading
return {
"users": [
{"name": "Alice", "age": 25, "city": "New York"},
{"name": "Bob", "age": 30, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
],
"metadata": {"version": "1.0", "created": "2025-01-01"}
}
def validate_data(self, data):
print("✅ Validating JSON data structure")
# Check if data is a dictionary with users array
if not isinstance(data, dict) or "users" not in data:
return False
# Check if users is a list
return isinstance(data["users"], list)
def transform_data(self, data):
print("🔄 Transforming JSON data (adding processed flag)")
# Add processed timestamp to each user
transformed_data = data.copy()
for user in transformed_data["users"]:
user["processed"] = True
user["processed_at"] = "2025-01-01T12:00:00Z"
return transformed_data
def save_data(self, data, destination):
print(f"💾 Saving JSON data to {destination}")
# Pretty print the JSON
print(json.dumps(data, indent=2))
# What we accomplished in this step:
# - Implemented JSONProcessor with JSON-specific logic
# - Showed how different formats can use the same template
# Step 5: Test the Template Method pattern
# ===============================================================================
# Explanation:
# Let's test both processors to see how the template method works
# with different implementations.
from abc import ABC, abstractmethod
import json
class DataProcessor(ABC):
def process_data(self, source, destination):
"""Template method that defines the data processing algorithm"""
print(f"Starting data processing from {source} to {destination}")
# Step 1: Load data
data = self.load_data(source)
# Step 2: Validate data
if self.validate_data(data):
# Step 3: Transform data
transformed_data = self.transform_data(data)
# Step 4: Save data
self.save_data(transformed_data, destination)
print("Data processing completed successfully")
else:
print("Data validation failed")
@abstractmethod
def load_data(self, source):
pass
@abstractmethod
def validate_data(self, data):
pass
@abstractmethod
def transform_data(self, data):
pass
@abstractmethod
def save_data(self, data, destination):
pass
class CSVProcessor(DataProcessor):
def load_data(self, source):
print(f"📄 Loading CSV data from {source}")
return [
["Name", "Age", "City"],
["Alice", "25", "New York"],
["Bob", "30", "San Francisco"],
["Charlie", "35", "Chicago"]
]
def validate_data(self, data):
print("✅ Validating CSV data structure")
if len(data) < 2:
return False
header_length = len(data[0])
return all(len(row) == header_length for row in data)
def transform_data(self, data):
print("🔄 Transforming CSV data (converting to uppercase)")
transformed = [data[0]]
for row in data[1:]:
transformed.append([cell.upper() if isinstance(cell, str) else cell for cell in row])
return transformed
def save_data(self, data, destination):
print(f"💾 Saving CSV data to {destination}")
for row in data:
print(f" {','.join(row)}")
class JSONProcessor(DataProcessor):
def load_data(self, source):
print(f"📋 Loading JSON data from {source}")
return {
"users": [
{"name": "Alice", "age": 25, "city": "New York"},
{"name": "Bob", "age": 30, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
],
"metadata": {"version": "1.0", "created": "2025-01-01"}
}
def validate_data(self, data):
print("✅ Validating JSON data structure")
if not isinstance(data, dict) or "users" not in data:
return False
return isinstance(data["users"], list)
def transform_data(self, data):
print("🔄 Transforming JSON data (adding processed flag)")
transformed_data = data.copy()
for user in transformed_data["users"]:
user["processed"] = True
user["processed_at"] = "2025-01-01T12:00:00Z"
return transformed_data
def save_data(self, data, destination):
print(f"💾 Saving JSON data to {destination}")
print(json.dumps(data, indent=2))
# Test the Template Method pattern:
print("=== Testing CSV Processor ===")
csv_processor = CSVProcessor()
csv_processor.process_data("data.csv", "output.csv")
print("\n=== Testing JSON Processor ===")
json_processor = JSONProcessor()
json_processor.process_data("data.json", "output.json")
# Demonstrate polymorphism:
print("\n=== Polymorphic Processing ===")
processors = [CSVProcessor(), JSONProcessor()]
sources = ["employees.csv", "users.json"]
destinations = ["processed_employees.csv", "processed_users.json"]
for processor, source, dest in zip(processors, sources, destinations):
print(f"\nProcessing with {type(processor).__name__}:")
processor.process_data(source, dest)
# What we accomplished in this step:
# - Tested both processors with the same template method
# - Demonstrated polymorphism with different processor types
# - Showed how the algorithm structure remains consistent
# ===============================================================================
# CONGRATULATIONS!
#
# You've successfully completed the step-by-step solution!
#
# Key concepts learned:
# - Template Method pattern implementation
# - Abstract methods as customization points
# - Algorithm structure preservation with flexible implementation
# - Polymorphism through abstract base classes
# - Code reuse through inheritance and abstraction
#
# Try it yourself:
# 1. Start with Step 1 and code along
# 2. Test each step before moving to the next
# 3. Understand WHY each step is necessary
# 4. Experiment with modifications (try adding XMLProcessor or DatabaseProcessor!)
#
# Remember: The best way to learn is by doing!
# ===============================================================================