-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathsingleton.cpp
88 lines (82 loc) · 1.68 KB
/
singleton.cpp
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
#include <iostream>
#include <string>
using namespace std;
// Default Classes
class Device
{
public:
virtual void send(string data) = 0;
virtual int setSpeed(int value) = 0;
virtual int getSpeed() = 0;
};
class Wifi : public Device
{
public:
int speed;
static Wifi* thisInstance;
Wifi()
{
speed = 100;
}
int setSpeed(int value)
{
speed = value;
}
int getSpeed()
{
return speed;
}
void send(string data)
{
cout<<"Sent By Wifi: "<<data<<" Speed: "<<speed<<endl;
}
// Singleton Design Pattern
static Device* instance()
{
if (!thisInstance){
thisInstance = new Wifi;
}
return thisInstance;
}
};
class Bluetooth : public Device
{
public:
int speed;
static Bluetooth* thisInstance;
Bluetooth(){
speed = 8;
}
int setSpeed(int value)
{
speed = value;
}
int getSpeed()
{
return speed;
}
void send(string data)
{
cout<<"Sent By Bluetooth: "<<data<<" Speed: "<<speed<<endl;
}
// Singleton Design Pattern
static Bluetooth *instance()
{
if (!thisInstance){
thisInstance = new Bluetooth;
}
return thisInstance;
}
};
// Singleton Design Pattern Just added in to the every object
// Problem: access same object everywhere
// Solution: Add that to Object
Bluetooth *Bluetooth::thisInstance = 0;
Wifi *Wifi::thisInstance = 0;
int main()
{
Bluetooth::instance()->setSpeed(20);
Bluetooth::instance()->send("First Object");
Bluetooth::instance()->send("Second Object");
cout<<"Second Object should be same as the first one"<<endl;
}