C# में Interface सबसे important concepts में से एक है—
खासकर बड़े systems में, जहाँ कई models, कई devices, कई logics होते हैं।
Interface = Contract
जो class कहती है:
“मैं इस rules को follow करूँगी!”
बिना interface बड़े projects को maintain करना मुश्किल हो जाता है।
आज हम इसे super easy तरीके + आपके GPS Server project के real example से समझेंगे।
Interface =
✔ सिर्फ नाम
✔ सिर्फ structure
✔ कोई implementation नहीं
Class को बोलता है:
“तुम्हें ये methods ज़रूर बनाने हैं!”
interface IDevice
{
void Connect();
void ProcessPacket(string pkt);
}
Class जो इसे inherit करेगी,
उसे ये दोनों methods लाज़मी बनाने होंगे।
✔ Different classes में same method नाम चाहते हो
✔ Common behaviour enforce करना हो
✔ Plug-and-play architecture बनाना हो
✔ Multi-device/multi-model systems बनाना हो
✔ Future में नए devices जोड़ना आसान हो
Interfaces आपकी system की आधारशिला बन जाते हैं।
आपके पास कई devices हैं:
G17
S15
A20
TR06
LK209
हर device का packet format अलग,
लेकिन काम common:
Connect
Parse packet
Extract location
Send response
Update battery
इसलिए एक Common Interface बनाते हैं।
interface IGPSProtocol
{
void Parse(string packet);
double GetLatitude();
double GetLongitude();
int GetBattery();
}
अब चाहे G17 हो या S15 →
उन्हें ये methods बनाना ही है।
class G17Protocol : IGPSProtocol
{
public void Parse(string packet)
{
// G17 packet parsing
}
public double GetLatitude() => 26.85;
public double GetLongitude() => 80.94;
public int GetBattery() => 89;
}
class S15Protocol : IGPSProtocol
{
public void Parse(string packet)
{
// S15 specific parsing
}
public double GetLatitude() => 26.90;
public double GetLongitude() => 80.95;
public int GetBattery() => 75;
}
आपका server code बिना device जाने काम करेगा:
void ProcessDevice(IGPSProtocol device, string packet)
{
device.Parse(packet);
Console.WriteLine(device.GetLatitude());
}
Call:
ProcessDevice(new G17Protocol(), pkt);
ProcessDevice(new S15Protocol(), pkt);
Server को फर्क नहीं पड़ता कि:
ये G17 है
या S15
या future में कोई नया मॉडल
बस interface follow होना चाहिए।
Paytm
Google Pay
PhonePe
Card
Wallet
हर provider अपने तरीके से payment करता है →
लेकिन एक ही interface follow करता है।
EmailSender
SMSSender
WhatsAppSender
Common Interface: ISender.
Different tax rules → same interface.
All exams implement IExamination.
| Feature | Interface | Inheritance |
|---|---|---|
| Purpose | Contract enforce | Code reuse |
| Implementation | No | Yes |
| Multiple inheritance allowed? | ✔ Yes | ❌ No |
| Used for | Behaviour define | Common features |
✔ Interface → “क्या-क्या करना है?”
✔ Inheritance → “कैसे करना है?”
Interface आपके project को:
Future-proof
Scalable
Maintainable
Clean
Modular
बनाता है।
GPS Server जैसे बड़े systems में Interface अनिवार्य है।
एक बार interface बना दिया →
किसी भी नए Device Model को plug-in करना बहुत आसान।
0 Comments
Thanks for Commenting on our blogs, we will revert back with answer of your query.
EmojiThanks & Regards
Sonu Yadav