Aiwatar da SOLID ƙa'idodi a cikin C #: Misalai da Mafi kyawun Ayyuka

Single Responsibility Principle(SRP)

Wannan ka'ida ta bayyana cewa kowane aji yakamata ya kasance yana da alhakin guda ɗaya. Yana jaddada cewa aji ya kamata ya yi takamaiman aiki ɗaya kuma ba shi da dalilai da yawa don canzawa.

Misali: Sarrafa bayanan mai amfani da aika sanarwar imel.

class UserManager {  
  public void CreateUser(UserData userData) {  
    // Logic to create a user  
  }  
}  
  
class EmailService {  
  public void SendEmail(EmailData emailData) {  
    // Logic to send an email  
  }  
}  

Open/Closed Principle(OCP)

Wannan ƙa'ida tana ƙarfafa faɗaɗa ayyuka ta ƙara sabon lamba maimakon canza lambar da ke akwai.

Misali: Karɓar hanyoyin biyan kuɗi daban-daban a cikin aikace-aikacen kasuwancin e-commerce.

abstract class PaymentProcessor {  
  public abstract void ProcessPayment();  
}  
  
class CreditCardPaymentProcessor: PaymentProcessor {  
  public override void ProcessPayment() {  
    // Logic to process credit card payment  
  }  
}  
  
class PayPalPaymentProcessor: PaymentProcessor {  
  public override void ProcessPayment() {  
    // Logic to process PayPal payment  
  }  
}  

Liskov Substitution Principle(LSP)

Wannan ƙa'ida ta tabbatar da cewa abubuwan da aka samo asali yakamata su kasance a musanya su da abubuwan ajin tushe ba tare da yin tasiri ga daidaiton shirin ba.

Misali: Sarrafar da siffofi na geometric.

abstract class Shape {  
  public abstract double CalculateArea();  
}  
  
class Rectangle: Shape {  
  public override double CalculateArea() {  
    // Logic to calculate area of rectangle  
  }  
}  
  
class Square: Shape {  
  public override double CalculateArea() {  
    // Logic to calculate area of square  
  }  
}  

Interface Segregation Principle(ISP)

Wannan ƙa'idar tana ba da shawarar ɓata musaya zuwa ƙanana don guje wa tilasta azuzuwan aiwatar da hanyoyin da ba sa buƙata.

Misali: Interfaces don ɗaukakawa da nuna bayanai.

interface IUpdateableFeature {  
  void UpdateFeature();  
}  
  
interface IDisplayableFeature {  
  void DisplayFeature();  
}  

Dependency Inversion Principle(DIP)

Wannan ƙa'idar tana ba da shawarar yin amfani da allurar dogaro don sarrafa abin dogaro.

Misali: Amfani da allurar dogaro don sarrafa abin dogaro.

class OrderProcessor {  
  private readonly DBConnection _dbConnection;  
  private readonly EmailService _emailService;  
  
  public OrderProcessor(DBConnection dbConnection, EmailService emailService) {  
    _dbConnection = dbConnection;  
    _emailService = emailService;  
  }  
}  

Ka tuna cewa yin amfani da SOLID ka'idoji a cikin C # ya kamata a yi shi cikin sassauƙa bisa takamaiman manufar aikin ku da fahimtar ku da SOLID C #.