Single Responsibility Principle(SRP)
Kanuni hii inasema kwamba kila darasa linapaswa kuwa na jukumu moja. Inasisitiza kwamba darasa linapaswa kufanya kazi moja maalum na lisiwe na sababu nyingi za kubadilika.
Mfano: Kusimamia maelezo ya mtumiaji na kutuma arifa za barua pepe.
class UserManager {
void createUser(UserData userData) {
// Logic for creating a user
}
}
class EmailService {
void sendEmail(EmailData emailData) {
// Logic for sending an email
}
}
Open/Closed Principle(OCP)
Kanuni hii inahimiza kupanua utendakazi kwa kuongeza msimbo mpya badala ya kurekebisha msimbo uliopo.
Mfano: Kushughulikia mbinu tofauti za malipo katika programu ya biashara ya mtandaoni.
abstract class PaymentProcessor {
abstract void processPayment();
}
class CreditCardPaymentProcessor extends PaymentProcessor {
void processPayment() {
// Logic for processing credit card payment
}
}
class PayPalPaymentProcessor extends PaymentProcessor {
void processPayment() {
// Logic for processing PayPal payment
}
}
Liskov Substitution Principle(LSP)
Kanuni hii inadai kuwa vipengee vya darasa linalotokana vinapaswa kubadilishwa kwa vitu vya darasa la msingi bila kuathiri usahihi wa programu.
Mfano: Kusimamia maumbo ya kijiometri.
abstract class Shape {
abstract double area();
}
class Rectangle extends Shape {
double area() {
// Logic for calculating area of rectangle
}
}
class Square extends Shape {
double area() {
// Logic for calculating area of square
}
}
Kanuni ya Kutenganisha Kiolesura(ISP)
Kanuni hii inashauri kuvunja miingiliano kuwa ndogo ili kuzuia kulazimisha madarasa kutekeleza njia ambazo hazihitaji.
Mfano: Violesura vya kusasisha na kuonyesha data.
interface UpdateableFeature {
void updateFeature();
}
interface DisplayableFeature {
void displayFeature();
}
Dependency Inversion Principle(DIP)
Kanuni hii inapendekeza kutumia sindano ya utegemezi kudhibiti utegemezi.
Mfano: Kutumia sindano ya utegemezi kudhibiti utegemezi.
class OrderProcessor {
private final DBConnection dbConnection;
private final EmailService emailService;
OrderProcessor(DBConnection dbConnection, EmailService emailService) {
this.dbConnection = dbConnection;
this.emailService = emailService;
}
}
Kumbuka kwamba kutumia SOLID kanuni ndani Java kunapaswa kufanywa kwa urahisi kulingana na madhumuni mahususi ya mradi wako na uelewa wako wa SOLID na Java.