Repository navigation
Expand file tree
/
Copy pathFactoryPatternDemo.java
More file actions
575 lines (478 loc) · 17.3 KB
/
Copy pathFactoryPatternDemo.java
File metadata and controls
575 lines (478 loc) · 17.3 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
package patterns;
/**
* FactoryPatternDemo - Demonstrates the Factory Design Pattern
*
* The Factory pattern provides an interface for creating objects
* without exposing the instantiation logic to the client.
*
* This demo covers:
* - Simple Factory
* - Factory Method Pattern
* - Abstract Factory Pattern
* - Real-world applications
*
* @author Java Examples Project
* @version 1.0
*/
// Product interface
interface Vehicle {
void start();
void stop();
void displayInfo();
String getType();
}
// Concrete Products
class Car implements Vehicle {
private String model;
private int doors;
public Car(String model, int doors) {
this.model = model;
this.doors = doors;
}
@Override
public void start() {
System.out.println("Car engine started with key ignition");
}
@Override
public void stop() {
System.out.println("Car engine stopped");
}
@Override
public void displayInfo() {
System.out.println("Car - Model: " + model + ", Doors: " + doors);
}
@Override
public String getType() {
return "Car";
}
}
class Motorcycle implements Vehicle {
private String brand;
private int engineCC;
public Motorcycle(String brand, int engineCC) {
this.brand = brand;
this.engineCC = engineCC;
}
@Override
public void start() {
System.out.println("Motorcycle started with kick/electric start");
}
@Override
public void stop() {
System.out.println("Motorcycle engine stopped");
}
@Override
public void displayInfo() {
System.out.println("Motorcycle - Brand: " + brand + ", Engine: " + engineCC + "cc");
}
@Override
public String getType() {
return "Motorcycle";
}
}
class Truck implements Vehicle {
private String model;
private double loadCapacity;
public Truck(String model, double loadCapacity) {
this.model = model;
this.loadCapacity = loadCapacity;
}
@Override
public void start() {
System.out.println("Truck diesel engine started");
}
@Override
public void stop() {
System.out.println("Truck engine stopped");
}
@Override
public void displayInfo() {
System.out.println("Truck - Model: " + model + ", Load Capacity: " + loadCapacity + " tons");
}
@Override
public String getType() {
return "Truck";
}
}
// 1. Simple Factory
class SimpleVehicleFactory {
public static Vehicle createVehicle(String type) {
switch (type.toLowerCase()) {
case "car":
return new Car("Sedan", 4);
case "motorcycle":
return new Motorcycle("SportBike", 600);
case "truck":
return new Truck("Heavy Duty", 10.0);
default:
throw new IllegalArgumentException("Unknown vehicle type: " + type);
}
}
public static Vehicle createVehicle(String type, String... params) {
switch (type.toLowerCase()) {
case "car":
String carModel = params.length > 0 ? params[0] : "Default";
int doors = params.length > 1 ? Integer.parseInt(params[1]) : 4;
return new Car(carModel, doors);
case "motorcycle":
String bikeBrand = params.length > 0 ? params[0] : "Default";
int engineCC = params.length > 1 ? Integer.parseInt(params[1]) : 500;
return new Motorcycle(bikeBrand, engineCC);
case "truck":
String truckModel = params.length > 0 ? params[0] : "Default";
double capacity = params.length > 1 ? Double.parseDouble(params[1]) : 5.0;
return new Truck(truckModel, capacity);
default:
throw new IllegalArgumentException("Unknown vehicle type: " + type);
}
}
}
// 2. Factory Method Pattern
// Abstract Creator
abstract class VehicleFactory {
// Factory method - to be implemented by concrete factories
public abstract Vehicle createVehicle();
// Template method that uses the factory method
public Vehicle orderVehicle() {
Vehicle vehicle = createVehicle();
// Common operations for all vehicles
System.out.println("Processing order for: " + vehicle.getType());
vehicle.displayInfo();
System.out.println("Quality check passed");
System.out.println("Vehicle ready for delivery");
return vehicle;
}
}
// Concrete Creators
class CarFactory extends VehicleFactory {
private String model;
private int doors;
public CarFactory(String model, int doors) {
this.model = model;
this.doors = doors;
}
@Override
public Vehicle createVehicle() {
return new Car(model, doors);
}
}
class MotorcycleFactory extends VehicleFactory {
private String brand;
private int engineCC;
public MotorcycleFactory(String brand, int engineCC) {
this.brand = brand;
this.engineCC = engineCC;
}
@Override
public Vehicle createVehicle() {
return new Motorcycle(brand, engineCC);
}
}
class TruckFactory extends VehicleFactory {
private String model;
private double loadCapacity;
public TruckFactory(String model, double loadCapacity) {
this.model = model;
this.loadCapacity = loadCapacity;
}
@Override
public Vehicle createVehicle() {
return new Truck(model, loadCapacity);
}
}
// 3. Abstract Factory Pattern
// Abstract products for different categories
interface Engine {
void start();
void stop();
String getType();
}
interface Transmission {
void shiftGear(int gear);
String getType();
}
// Concrete products for Economy category
class EconomyEngine implements Engine {
@Override
public void start() {
System.out.println("Economy engine started - 4 cylinder, fuel efficient");
}
@Override
public void stop() {
System.out.println("Economy engine stopped");
}
@Override
public String getType() {
return "Economy Engine";
}
}
class EconomyTransmission implements Transmission {
@Override
public void shiftGear(int gear) {
System.out.println("Economy CVT transmission shifted to gear: " + gear);
}
@Override
public String getType() {
return "CVT Transmission";
}
}
// Concrete products for Sports category
class SportsEngine implements Engine {
@Override
public void start() {
System.out.println("Sports engine started - V6 turbo, high performance");
}
@Override
public void stop() {
System.out.println("Sports engine stopped");
}
@Override
public String getType() {
return "Sports Engine";
}
}
class SportsTransmission implements Transmission {
@Override
public void shiftGear(int gear) {
System.out.println("Sports manual transmission shifted to gear: " + gear);
}
@Override
public String getType() {
return "Manual Transmission";
}
}
// Concrete products for Luxury category
class LuxuryEngine implements Engine {
@Override
public void start() {
System.out.println("Luxury engine started - V8, smooth and powerful");
}
@Override
public void stop() {
System.out.println("Luxury engine stopped");
}
@Override
public String getType() {
return "Luxury Engine";
}
}
class LuxuryTransmission implements Transmission {
@Override
public void shiftGear(int gear) {
System.out.println("Luxury automatic transmission smoothly shifted to gear: " + gear);
}
@Override
public String getType() {
return "Automatic Transmission";
}
}
// Abstract Factory
interface VehicleComponentFactory {
Engine createEngine();
Transmission createTransmission();
}
// Concrete Factories
class EconomyVehicleFactory implements VehicleComponentFactory {
@Override
public Engine createEngine() {
return new EconomyEngine();
}
@Override
public Transmission createTransmission() {
return new EconomyTransmission();
}
}
class SportsVehicleFactory implements VehicleComponentFactory {
@Override
public Engine createEngine() {
return new SportsEngine();
}
@Override
public Transmission createTransmission() {
return new SportsTransmission();
}
}
class LuxuryVehicleFactory implements VehicleComponentFactory {
@Override
public Engine createEngine() {
return new LuxuryEngine();
}
@Override
public Transmission createTransmission() {
return new LuxuryTransmission();
}
}
// Vehicle Configurator using Abstract Factory
class VehicleConfigurator {
private Engine engine;
private Transmission transmission;
public VehicleConfigurator(VehicleComponentFactory factory) {
this.engine = factory.createEngine();
this.transmission = factory.createTransmission();
}
public void startVehicle() {
System.out.println("Starting vehicle configuration:");
System.out.println("Engine: " + engine.getType());
System.out.println("Transmission: " + transmission.getType());
engine.start();
transmission.shiftGear(1);
}
public void stopVehicle() {
transmission.shiftGear(0);
engine.stop();
System.out.println("Vehicle stopped");
}
}
public class FactoryPatternDemo {
/**
* Demonstrates Simple Factory pattern
*/
public static void demonstrateSimpleFactory() {
System.out.println("=== SIMPLE FACTORY PATTERN ===");
// Create vehicles using simple factory
Vehicle car = SimpleVehicleFactory.createVehicle("car");
Vehicle motorcycle = SimpleVehicleFactory.createVehicle("motorcycle");
Vehicle truck = SimpleVehicleFactory.createVehicle("truck");
// Test vehicles
Vehicle[] vehicles = {car, motorcycle, truck};
for (Vehicle vehicle : vehicles) {
vehicle.displayInfo();
vehicle.start();
vehicle.stop();
System.out.println();
}
// Create vehicles with custom parameters
System.out.println("Custom vehicles:");
Vehicle customCar = SimpleVehicleFactory.createVehicle("car", "BMW X5", "5");
Vehicle customBike = SimpleVehicleFactory.createVehicle("motorcycle", "Harley Davidson", "1200");
customCar.displayInfo();
customBike.displayInfo();
}
/**
* Demonstrates Factory Method pattern
*/
public static void demonstrateFactoryMethod() {
System.out.println("\n=== FACTORY METHOD PATTERN ===");
// Create different factories
VehicleFactory carFactory = new CarFactory("Tesla Model 3", 4);
VehicleFactory motorcycleFactory = new MotorcycleFactory("Kawasaki Ninja", 650);
VehicleFactory truckFactory = new TruckFactory("Volvo FH", 25.0);
// Order vehicles through factories
System.out.println("Ordering vehicles through factories:");
Vehicle orderedCar = carFactory.orderVehicle();
System.out.println();
Vehicle orderedMotorcycle = motorcycleFactory.orderVehicle();
System.out.println();
Vehicle orderedTruck = truckFactory.orderVehicle();
System.out.println();
// Test the ordered vehicles
System.out.println("Testing ordered vehicles:");
orderedCar.start();
orderedMotorcycle.start();
orderedTruck.start();
}
/**
* Demonstrates Abstract Factory pattern
*/
public static void demonstrateAbstractFactory() {
System.out.println("\n=== ABSTRACT FACTORY PATTERN ===");
// Create different vehicle configurations
VehicleComponentFactory economyFactory = new EconomyVehicleFactory();
VehicleComponentFactory sportsFactory = new SportsVehicleFactory();
VehicleComponentFactory luxuryFactory = new LuxuryVehicleFactory();
// Configure vehicles using different factories
System.out.println("1. Economy Vehicle Configuration:");
VehicleConfigurator economyVehicle = new VehicleConfigurator(economyFactory);
economyVehicle.startVehicle();
economyVehicle.stopVehicle();
System.out.println("\n2. Sports Vehicle Configuration:");
VehicleConfigurator sportsVehicle = new VehicleConfigurator(sportsFactory);
sportsVehicle.startVehicle();
sportsVehicle.stopVehicle();
System.out.println("\n3. Luxury Vehicle Configuration:");
VehicleConfigurator luxuryVehicle = new VehicleConfigurator(luxuryFactory);
luxuryVehicle.startVehicle();
luxuryVehicle.stopVehicle();
}
/**
* Demonstrates real-world factory usage scenarios
*/
public static void demonstrateRealWorldScenarios() {
System.out.println("\n=== REAL-WORLD SCENARIOS ===");
// Scenario 1: Vehicle rental system
System.out.println("Scenario 1: Vehicle Rental System");
String[] customerRequests = {"car", "motorcycle", "truck", "car"};
for (int i = 0; i < customerRequests.length; i++) {
System.out.println("\nCustomer " + (i + 1) + " requested: " + customerRequests[i]);
try {
Vehicle rentalVehicle = SimpleVehicleFactory.createVehicle(customerRequests[i]);
System.out.println("Assigned vehicle:");
rentalVehicle.displayInfo();
System.out.println("Vehicle ready for rental");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
// Scenario 2: Vehicle manufacturing line
System.out.println("\n\nScenario 2: Manufacturing Line");
VehicleFactory[] productionLine = {
new CarFactory("Honda Civic", 4),
new CarFactory("Toyota Camry", 4),
new MotorcycleFactory("Yamaha R1", 1000),
new TruckFactory("Mercedes Actros", 40.0)
};
System.out.println("Daily production:");
for (int i = 0; i < productionLine.length; i++) {
System.out.println("\nProduction slot " + (i + 1) + ":");
productionLine[i].orderVehicle();
}
}
/**
* Analyzes factory pattern characteristics
*/
public static void analyzeFactoryPatterns() {
System.out.println("\n=== FACTORY PATTERN ANALYSIS ===");
System.out.println("1. Simple Factory:");
System.out.println(" Pros: Easy to implement, centralizes object creation");
System.out.println(" Cons: Violates Open/Closed Principle, not a true design pattern");
System.out.println(" Use when: Simple object creation with few types");
System.out.println("\n2. Factory Method:");
System.out.println(" Pros: Follows Open/Closed Principle, flexible and extensible");
System.out.println(" Cons: Can create complex class hierarchies");
System.out.println(" Use when: Need to delegate object creation to subclasses");
System.out.println("\n3. Abstract Factory:");
System.out.println(" Pros: Creates families of related objects, ensures consistency");
System.out.println(" Cons: Complex to implement, difficult to extend");
System.out.println(" Use when: Need to create families of related objects");
System.out.println("\nCommon Benefits:");
System.out.println("• Loose coupling between client and concrete classes");
System.out.println("• Centralizes object creation logic");
System.out.println("• Easier to maintain and extend");
System.out.println("• Supports polymorphism");
System.out.println("\nReal-world Applications:");
System.out.println("• GUI framework components");
System.out.println("• Database connection creation");
System.out.println("• Parser creation based on file type");
System.out.println("• Game object creation");
System.out.println("• Plugin architecture");
}
/**
* Main method demonstrating the Factory patterns
* @param args command line arguments
*/
public static void main(String[] args) {
System.out.println("Factory Design Pattern Demonstration");
System.out.println("===================================");
demonstrateSimpleFactory();
demonstrateFactoryMethod();
demonstrateAbstractFactory();
demonstrateRealWorldScenarios();
analyzeFactoryPatterns();
System.out.println("\n=== SUMMARY ===");
System.out.println("Factory patterns provide flexible ways to create objects:");
System.out.println("• Simple Factory: Basic creation with static methods");
System.out.println("• Factory Method: Delegates creation to subclasses");
System.out.println("• Abstract Factory: Creates families of related objects");
System.out.println("Choose based on complexity and extensibility requirements.");
}
}