-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructural_patterns.cpp
More file actions
619 lines (547 loc) · 26.5 KB
/
Copy pathstructural_patterns.cpp
File metadata and controls
619 lines (547 loc) · 26.5 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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// =============================================================================
// STRUCTURAL PATTERNS - C++ Implementations
// Based on: Design Patterns: Elements of Reusable Object-Oriented Software
// Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (GoF)
//
// Patterns covered (7):
// Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy
// =============================================================================
#include <memory>
#include <print>
#include <string>
#include <unordered_map>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#endif
/// ─────────────────────────────────────────────────────────────────────────────
/// PATTERN 6: ADAPTER (Object form)
/// ─────────────────────────────────────────────────────────────────────────────
///
/// PROJECT: Legacy Payment Gateway Integration
/// Your app uses a PaymentProcessor interface (charge / refund). You need to
/// integrate StripeAPI, a third-party SDK with completely different method
/// names (makePayment / reverseCharge). You cannot modify the SDK.
///
/// WHY ADAPTER?
/// ✓ You have an existing class (StripeAPI / Adaptee) whose interface
/// doesn't match what the client expects (PaymentProcessor / Target).
/// ✓ You cannot change StripeAPI (third-party SDK).
/// ✓ The mismatch is interface-level, not a fundamental incompatibility.
///
/// OBJECT vs CLASS ADAPTER: Using the Object Adapter (composition) because
/// C++ multiple inheritance would work for Class Adapter but is less flexible;
/// this Adapter could wrap StripeSubclass without recompiling.
///
/// ALTERNATIVES RULED OUT:
/// Façade: Façade wraps a *subsystem*; here we adapt ONE object's interface.
/// Bridge: plans for multiple implementations upfront; this is
/// after-the-fact integration of an unforeseen third-party.
/// ─────────────────────────────────────────────────────────────────────────────
namespace adapter {
/// Target interface: what our application code expects
struct PaymentProcessor {
virtual void charge(double amount) = 0;
virtual void refund(double amount) = 0;
virtual ~PaymentProcessor() = default;
};
/// Adaptee: the existing third-party Stripe SDK (can't modify)
struct StripeAPI {
void makePayment(double usd) { std::println("[Stripe] Processing payment of ${}", usd); }
void reverseCharge(double usd) { std::println("[Stripe] Reversing charge of ${}", usd); }
};
/// Object Adapter: wraps StripeAPI, exposes PaymentProcessor interface
struct StripeAdapter : PaymentProcessor {
explicit StripeAdapter(std::shared_ptr<StripeAPI> stripe) : m_stripe(stripe) {}
void charge(double amount) override { m_stripe->makePayment(amount); }
void refund(double amount) override { m_stripe->reverseCharge(amount); }
private:
std::shared_ptr<StripeAPI> m_stripe;
};
/// Client: only knows PaymentProcessor; unaware of Stripe internals
void processOrder(PaymentProcessor& prc, double total) {
std::print("Charging customer: ");
prc.charge(total);
}
void demo() {
std::println("\n Adapter: Legacy Payment Gateway ");
auto stripeSDK = std::make_shared<StripeAPI>();
StripeAdapter adp(stripeSDK);
processOrder(adp, 99.99);
adp.refund(15.00);
}
} // namespace adapter
/// ─────────────────────────────────────────────────────────────────────────────
/// PATTERN 7: BRIDGE
/// ─────────────────────────────────────────────────────────────────────────────
///
/// PROJECT: Remote Control for Electronic Devices
/// You need remotes (BasicRemote, AdvancedRemote) that control devices (TV,
/// Radio, Projector). If Remote subclasses TV and Radio, you get N×M classes
/// (BasicTVRemote, AdvancedTVRemote, BasicRadioRemote…). Bridge flattens
/// this to N+M.
///
/// WHY BRIDGE?
/// ✓ Two independent dimensions that both need subclassing: Remote type and
/// Device type. Bridge was designed for exactly this N×M to N+M reduction.
/// ✓ You want to select the device at runtime (plug the remote into any
/// device). ✓ Both hierarchies will grow independently (new remotes, new
/// devices).
///
/// BRIDGE vs ADAPTER:
/// Adapter: retrofits after classes unexpectedly need to interoperate.
/// Bridge: planned upfront because you KNOW both axes will vary.
/// Slogan: "Adapter after; Bridge before."
/// ─────────────────────────────────────────────────────────────────────────────
namespace bridge {
/// Implementor interface: the "device" axis
struct Device {
virtual void powerOn() = 0;
virtual void powerOff() = 0;
virtual void setVolume(int vol) = 0;
virtual std::string name() const = 0;
virtual ~Device() = default;
};
struct TV : Device {
void powerOn() override { std::println("[TV] Power ON"); }
void powerOff() override { std::println("[TV] Power OFF"); }
void setVolume(int vol) override { std::println("[TV] Volume → {}", vol); }
std::string name() const override { return "TV"; }
};
struct Radio : Device {
void powerOn() override { std::println("[Radio] Power ON"); }
void powerOff() override { std::println("[Radio] Power OFF"); }
void setVolume(int vol) override { std::println("[Radio] Volume → {}", vol); }
std::string name() const override { return "Radio"; }
};
/// Abstraction: the "remote" axis; holds the bridge to a Device
struct Remote {
explicit Remote(std::shared_ptr<Device> device) : m_device(device) {}
virtual void togglePower() { m_device->powerOn(); }
virtual void volumeUp() { m_device->setVolume(m_volume += 10); }
virtual ~Remote() = default;
protected:
std::shared_ptr<Device> m_device;
int m_volume = 50;
};
/// Refined Abstraction: extends Remote without touching Device
struct AdvancedRemote : Remote {
explicit AdvancedRemote(std::shared_ptr<Device> device) : Remote(device) {}
void mute() {
std::println("[AdvancedRemote] Muting {}", m_device->name());
m_device->setVolume(0);
}
};
void demo() {
std::println("\n Bridge: Remote Control & Devices ");
auto tvDev = std::make_shared<TV>();
auto radio = std::make_shared<Radio>();
Remote basicTVRemote(tvDev);
basicTVRemote.togglePower();
basicTVRemote.volumeUp();
AdvancedRemote advRadioRemote(radio);
advRadioRemote.togglePower();
advRadioRemote.mute();
}
} // namespace bridge
/// ─────────────────────────────────────────────────────────────────────────────
/// PATTERN 8: COMPOSITE
/// ─────────────────────────────────────────────────────────────────────────────
///
/// PROJECT: File System (Files and Folders)
/// A file system has Files (leaves) and Folders (composites containing other
/// Files or Folders). Printing the size of a Folder should recursively sum
/// sizes of all children - identical call for both File and Folder.
///
/// WHY COMPOSITE?
/// ✓ We have a classic part-whole hierarchy (Folder contains Files and
/// Folders), and we want to treat them uniformly via one interface.
/// ✓ "Display the size of X" should work whether X is a file or a folder.
/// ✓ Client code shouldn't ask "is this a file or a folder?" repeatedly.
///
/// DESIGN DECISION: Child management (add/remove) placed on the Component
/// interface for maximum transparency - Files implement them as no-ops.
/// Alternative: put only on Composite for type-safety, but then clients must
/// downcast. The book leans toward transparency here.
/// ─────────────────────────────────────────────────────────────────────────────
namespace composite {
/// Component: uniform interface for both leaves and composites
struct FileSystemNode {
std::string name;
explicit FileSystemNode(std::string nam) : name(std::move(nam)) {}
virtual long size() const = 0;
virtual void print(int indent = 0) const = 0;
virtual void add(std::shared_ptr<FileSystemNode>) { /* no-op for leaves */ }
virtual ~FileSystemNode() = default;
};
// Leaf
struct File : FileSystemNode {
long bytes;
File(std::string nam, long byt) : FileSystemNode(std::move(nam)), bytes(byt) {}
long size() const override { return bytes; }
void print(int indent) const override {
std::println("{}📄 {} ({} B)", std::string(indent, ' '), name, bytes);
}
};
// Composite
struct Folder : FileSystemNode {
std::vector<std::shared_ptr<FileSystemNode>> children;
explicit Folder(std::string nam) : FileSystemNode(std::move(nam)) {}
void add(std::shared_ptr<FileSystemNode> node) override { children.push_back(node); }
long size() const override {
long total = 0;
for (const auto& chd : children) total += chd->size();
return total;
}
void print(int indent) const override {
std::println("{}📁 {}/", std::string(indent, ' '), name);
for (const auto& chd : children) chd->print(indent + 4);
}
};
void demo() {
std::println("\n Composite: File System ");
auto root = std::make_shared<Folder>("root");
auto src = std::make_shared<Folder>("src");
auto docs = std::make_shared<Folder>("docs");
src->add(std::make_shared<File>("main.cpp", 4200));
src->add(std::make_shared<File>("utils.cpp", 1800));
docs->add(std::make_shared<File>("README.md", 900));
root->add(src);
root->add(docs);
root->add(std::make_shared<File>(".gitignore", 120));
root->print(0);
std::println("Total size: {} B", root->size());
}
} // namespace composite
/// ─────────────────────────────────────────────────────────────────────────────
/// PATTERN 9: DECORATOR
/// ─────────────────────────────────────────────────────────────────────────────
///
/// PROJECT: Coffee Shop Order System
/// Base beverages (Espresso, Drip Coffee) can have optional add-ons (Milk,
/// Vanilla Syrup, Whipped Cream). Every combination must compute cost and
/// description correctly. Subclassing each combination (EspressoWithMilk,
/// EspressoWithMilkAndVanilla…) would explode combinatorially.
///
/// WHY DECORATOR?
/// ✓ Responsibilities (add-ons) must be added dynamically and transparently.
/// ✓ Add-ons are optional and combinable - this is the textbook case.
/// ✓ Each Decorator wraps a Beverage and IS-A Beverage (same interface),
/// so they nest freely in any order.
///
/// DECORATOR vs INHERITANCE:
/// Inheritance gives you EspressoWithMilk at compile time.
/// Decorator gives you espresso + milk + vanilla at RUNTIME, mixed freely.
///
/// KEY LIABILITY: Decorator identity differs from the wrapped object.
/// `decorator == original` is false. Irrelevant here (we care about cost),
/// but to be aware of in identity-sensitive contexts.
/// ─────────────────────────────────────────────────────────────────────────────
namespace decorator {
// Component interface
struct Beverage {
virtual double cost() const = 0;
virtual std::string description() const = 0;
virtual ~Beverage() = default;
};
// Concrete Components (base beverages)
struct Espresso : Beverage {
double cost() const override { return 2.50; }
std::string description() const override { return "Espresso"; }
};
struct DripCoffee : Beverage {
double cost() const override { return 1.00; }
std::string description() const override { return "Drip Coffee"; }
};
/// Base Decorator: wraps a Beverage, IS-A Beverage
struct AddOnDecorator : Beverage {
explicit AddOnDecorator(std::unique_ptr<Beverage> bev) : m_beverage(std::move(bev)) {}
protected:
std::unique_ptr<Beverage> m_beverage;
};
// Concrete Decorators
struct Milk : AddOnDecorator {
explicit Milk(std::unique_ptr<Beverage> bev) : AddOnDecorator(std::move(bev)) {}
double cost() const override { return m_beverage->cost() + 0.30; }
std::string description() const override { return m_beverage->description() + ", Milk"; }
};
struct VanillaSyrup : AddOnDecorator {
explicit VanillaSyrup(std::unique_ptr<Beverage> bev) : AddOnDecorator(std::move(bev)) {}
double cost() const override { return m_beverage->cost() + 0.50; }
std::string description() const override { return m_beverage->description() + ", Vanilla"; }
};
struct WhippedCream : AddOnDecorator {
explicit WhippedCream(std::unique_ptr<Beverage> bev) : AddOnDecorator(std::move(bev)) {}
double cost() const override { return m_beverage->cost() + 0.75; }
std::string description() const override {
return m_beverage->description() + ", Whipped Cream";
}
};
void printOrder(const Beverage& bev) { std::println("{} - ${}", bev.description(), bev.cost()); }
void demo() {
std::println("\n Decorator: Coffee Shop Order System ");
// Plain espresso
auto order1 = std::make_unique<Espresso>();
printOrder(*order1);
// Espresso + Milk + Vanilla
std::unique_ptr<Beverage> order2 = std::make_unique<Espresso>();
order2 = std::make_unique<Milk>(std::move(order2));
order2 = std::make_unique<VanillaSyrup>(std::move(order2));
printOrder(*order2);
// Drip Coffee + Milk + Whipped Cream
std::unique_ptr<Beverage> order3 = std::make_unique<DripCoffee>();
order3 = std::make_unique<Milk>(std::move(order3));
order3 = std::make_unique<WhippedCream>(std::move(order3));
printOrder(*order3);
}
} // namespace decorator
/// ─────────────────────────────────────────────────────────────────────────────
/// PATTERN 10: FAÇADE
/// ─────────────────────────────────────────────────────────────────────────────
///
/// PROJECT: Home Theater System
/// A home theater has Amplifier, DVDPlayer, Projector, Screen, Lights - each
/// with its own complex API. To watch a movie, a user must call 8+ methods in
/// the right order. The Façade wraps this into watchMovie() and endMovie().
///
/// WHY FAÇADE?
/// ✓ Many subsystem classes with complex coordination for common tasks.
/// ✓ Clients want one simple interface without learning all subsystem classes.
/// ✓ Power users can still access subsystem classes directly.
///
/// FAÇADE vs MEDIATOR:
/// Façade: subsystem classes DON'T know about the Façade. One-way.
/// Mediator: colleagues actively communicate THROUGH the Mediator. Two-way.
///
/// FAÇADE vs ADAPTER:
/// Adapter: translates one object's interface. Façade defines a NEW
/// simplified interface over a whole subsystem.
/// ─────────────────────────────────────────────────────────────────────────────
namespace facade {
// Subsystem classes - complex, fine-grained
struct Amplifier {
void on() { std::println("Amplifier ON"); }
void setVolume(int vol) { std::println("Amplifier volume → {}", vol); }
void off() { std::println("Amplifier OFF"); }
};
struct DVDPlayer {
void on() { std::println("DVD Player ON"); }
void play(const std::string& mov) { std::println("DVD playing: {}", mov); }
void stop() { std::println("DVD stopped"); }
void off() { std::println("DVD Player OFF"); }
};
struct Projector {
void on() { std::println("Projector ON"); }
void widescreen() { std::println("Projector → widescreen mode"); }
void off() { std::println("Projector OFF"); }
};
struct Screen {
void lower() { std::println("Screen lowering..."); }
void raise() { std::println("Screen raising..."); }
};
struct Lights {
void dim(int level) { std::println("Lights dimmed to {}%", level); }
void on() { std::println("Lights ON"); }
};
/// Façade: simple interface over the whole subsystem
struct HomeTheaterFacade {
Amplifier amp;
DVDPlayer dvd;
Projector proj;
Screen screen;
Lights lights;
void watchMovie(const std::string& movie) {
std::println("Getting ready to watch \"{}\"...", movie);
lights.dim(10);
screen.lower();
proj.on();
proj.widescreen();
amp.on();
amp.setVolume(30);
dvd.on();
dvd.play(movie);
}
void endMovie() {
std::println("Shutting down theater...");
dvd.stop();
dvd.off();
amp.off();
proj.off();
screen.raise();
lights.on();
}
};
void demo() {
std::println("\n Façade: Home Theater System ");
HomeTheaterFacade theater;
theater.watchMovie("Interstellar");
std::println("... watching ...");
theater.endMovie();
}
} // namespace facade
/// ─────────────────────────────────────────────────────────────────────────────
/// PATTERN 11: FLYWEIGHT
/// ─────────────────────────────────────────────────────────────────────────────
///
/// PROJECT: Forest Renderer (Particle/Nature System)
/// Rendering a forest of 100,000 trees. Each tree has a species (name,
/// texture, color) - the INTRINSIC state - shared across all trees of that
/// species, plus a position (x, y) - the EXTRINSIC state - unique to each.
/// Without Flyweight: 100,000 objects each storing full texture data.
/// With Flyweight: 3-5 shared TreeType objects; positions passed in.
///
/// WHY FLYWEIGHT?
/// ✓ Large number of objects (100k+ trees).
/// ✓ Most state (species data, textures) is intrinsic (context-independent)
/// and shared across thousands of instances.
/// ✓ Identity does NOT matter - two Oaks at different positions are the same
/// TreeType flyweight.
///
/// INTRINSIC vs EXTRINSIC:
/// Intrinsic → stored IN the flyweight (species, texture, color)
/// Extrinsic → passed by the client when needed (x, y coordinates)
/// ─────────────────────────────────────────────────────────────────────────────
namespace flyweight {
/// Flyweight: stores INTRINSIC (shared) state only
struct TreeType {
std::string species, texture, color;
TreeType(std::string spc, std::string tex, std::string clr)
: species(std::move(spc)), texture(std::move(tex)), color(std::move(clr)) {}
// Extrinsic state (posX, posY) passed in - NOT stored here
void draw(int posX, int posY) const {
std::println("[{}@({},{})] color={} tex={}", species, posX, posY, color, texture);
}
};
/// FlyweightFactory: ensures sharing; manages the pool
struct TreeFactory {
std::unordered_map<std::string, std::shared_ptr<TreeType>> pool;
std::shared_ptr<TreeType> getTreeType(
const std::string& species, const std::string& texture, const std::string& color
) {
std::string key = species + "|" + texture + "|" + color;
auto itr = pool.find(key);
if (itr == pool.end()) {
std::println("[Factory] Creating new TreeType: {}", species);
pool[key] = std::make_shared<TreeType>(species, texture, color);
}
return pool[key];
}
size_t typeCount() const { return pool.size(); }
};
/// Tree: a thin context object; holds position + reference to shared flyweight
struct Tree {
int posX, posY;
std::shared_ptr<TreeType> type;
void draw() const { type->draw(posX, posY); }
};
void demo() {
std::println("\n Flyweight: Forest Renderer ");
TreeFactory factory;
std::vector<Tree> forest;
// Plant 6 trees of only 2 species - factory creates only 2 TreeType objects
auto oak = factory.getTreeType("Oak", "bark_oak.png", "dark_green");
auto pine = factory.getTreeType("Pine", "bark_pine.png", "blue_green");
factory.getTreeType("Oak", "bark_oak.png",
"dark_green"); // returned from pool
for (auto [tpX, tpY] : std::vector<std::pair<int, int>> {{10, 20}, {30, 40}, {50, 10}})
forest.push_back({tpX, tpY, oak});
for (auto [tpX, tpY] : std::vector<std::pair<int, int>> {{15, 55}, {70, 30}, {5, 80}})
forest.push_back({tpX, tpY, pine});
std::println(
"Drawing {} trees using {} TreeType flyweights:", forest.size(), factory.typeCount()
);
for (const auto& tre : forest) tre.draw();
}
} // namespace flyweight
/// ─────────────────────────────────────────────────────────────────────────────
/// PATTERN 12: PROXY
/// ─────────────────────────────────────────────────────────────────────────────
///
/// PROJECT: Virtual Image Loader (Lazy Loading Proxy)
/// A document editor displays images inline. Loading all images at startup
/// is slow - most won't be seen immediately. A Virtual Proxy stands in for
/// the real Image, providing size info for layout, but defers the expensive
/// disk load until the image is actually drawn on screen.
///
/// WHY PROXY (Virtual)?
/// ✓ The real object (Image) is expensive to create (disk I/O + decoding).
/// ✓ Creation should be deferred until the object is actually needed.
/// ✓ The Proxy exposes the SAME interface as the real Subject - the client
/// never knows whether it's talking to a real image or a proxy.
///
/// PROXY vs DECORATOR:
/// Both wrap an object with the same interface.
/// Decorator ADDS responsibilities.
/// Proxy CONTROLS ACCESS (lazy load, remote, protection, caching).
/// Intent is what differs.
/// ─────────────────────────────────────────────────────────────────────────────
namespace proxy {
// Subject interface
struct Image {
virtual void draw() const = 0;
virtual int width() const = 0;
virtual int height() const = 0;
virtual ~Image() = default;
};
/// Real Subject: expensive to construct
struct RealImage : Image {
std::string filename;
int m_width, m_height;
explicit RealImage(std::string fname)
: filename(std::move(fname)), m_width(1920), m_height(1080) {
// Simulate slow disk load
std::println("[RealImage] Loading '{}' from disk...", filename);
}
void draw() const override { std::println("[RealImage] Drawing '{}'", filename); }
int width() const override { return m_width; }
int height() const override { return m_height; }
};
/// Virtual Proxy: same interface; defers RealImage creation
struct ImageProxy : Image {
explicit ImageProxy(std::string fname) : m_filename(std::move(fname)), m_real(nullptr) {}
void draw() const override {
if (!m_real) {
std::println("[Proxy] First draw - loading real image now");
m_real = std::make_unique<RealImage>(m_filename);
}
m_real->draw();
}
int width() const override { return 1920; } // known without loading
int height() const override { return 1080; }
private:
std::string m_filename;
mutable std::unique_ptr<RealImage> m_real; // lazily initialized
};
void demo() {
std::println("\n Proxy: Virtual Image Loader ");
// Three images created (no disk I/O yet)
std::vector<std::unique_ptr<Image>> images;
images.push_back(std::make_unique<ImageProxy>("photo1.jpg"));
images.push_back(std::make_unique<ImageProxy>("photo2.jpg"));
images.push_back(std::make_unique<ImageProxy>("photo3.jpg"));
std::println("All image proxies created. No disk reads yet.");
std::println(
"Layout uses width/height without loading: {}x{}", images[0]->width(), images[0]->height()
);
std::println("\nUser scrolls to see image 0 and image 2:");
images[0]->draw(); // loads photo1.jpg
images[2]->draw(); // loads photo3.jpg
// photo2.jpg never loaded - user never scrolled there
std::println("\nDrawing image 0 again (already loaded, no disk I/O):");
images[0]->draw();
}
} // namespace proxy
/// Main function
int main() {
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
adapter::demo();
bridge::demo();
composite::demo();
decorator::demo();
facade::demo();
flyweight::demo();
proxy::demo();
return 0;
}