-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory-pattern.php
More file actions
81 lines (64 loc) · 1.91 KB
/
factory-pattern.php
File metadata and controls
81 lines (64 loc) · 1.91 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
<?php
// Definition:
// The Factory Pattern is a method to create objects from a central place
// without needing to know the specific class or how to create it.
// Without Factory Pattern - Problems
// Concrete Products
class Car
{
public function drive()
{
return "Driving a Car";
}
}
class Bike
{
public function drive()
{
return "Riding a Bike";
}
}
// Client Code (Without Factory Pattern)
$vehicle1 = new Car(); // Problem: Directly creating objects leads to tight coupling.
echo $vehicle1->drive(); // Output: "Driving a Car"
$vehicle2 = new Bike(); // Problem: Directly creating objects leads to code duplication.
echo $vehicle2->drive(); // Output: "Riding a Bike"
echo "\n\n";
// Solution: Factory Pattern
// Product Interface
interface Vehicle
{
public function drive();
}
// Concrete Products
class Car implements Vehicle
{
public function drive()
{
return "Driving a Car";
}
}
class Bike implements Vehicle
{
public function drive()
{
return "Riding a Bike";
}
}
// Factory Class
class VehicleFactory
{
public static function createVehicle($type)
{
if ($type == 'Car') return new Car();
if ($type == 'Bike') return new Bike();
throw new Exception("Invalid vehicle type");
}
}
// Client Code (Using Factory Pattern)
$vehicle = VehicleFactory::createVehicle('Car'); // Problem solved: Vehicle creation logic is centralized.
echo $vehicle->drive(); // Output: "Driving a Car"
// Problems Solved with Factory Pattern:
// - **Tight Coupling**: Client code no longer directly depends on the `Car` and `Bike` classes. The factory handles object creation.
// - **Code Duplication**: Object creation logic is centralized in the factory, avoiding repetition in client code.
// - **Difficult Maintenance**: Changes to vehicle creation logic are now made in the factory, so client code doesn't need to be modified.