publicvoid process(Order order){
MySQLOrderRepository repository = new MySQLOrderRepository();
ConfirmationEmailSender mailSender = new ConfirmationEmailSender();
if (order.isValid() && repository.save(order)) {
mailSender.sendConfirmationEmail(order);
}
}
}
Ushbu misolda bizning OrderProcessor MySQLOrderRepository va ConfirmationEmailSender ikkita aniq sinflariga bog'liq. Keling, ushbu sinflarning kodini beraylik:
publicclass MySQLOrderRepository {
publicboolean save(Order order) {
MySqlConnection connection = new MySqlConnection("database.url");
// buyurtmani ma'lumotlar bazasiga saqlash
return true;
}
}
publicclass ConfirmationEmailSender {
publicvoid sendConfirmationEmail(Order order) {
String name = order.getCustomerName();
String email = order.getCustomerEmail();
// Biz mijozga xat yuboramiz
}
}
Ushbu sinflar abstrakt deb nomlanishdan yiroq. Va DIP printsipi nuqtai nazaridan, kelajakda muayyan dasturlar bilan emas, balki ular bilan ishlashga imkon beradigan ba'zi bir abstraktsiyalarni yaratishdan boshlash to'g'ri bo'lar edi. Keling, ikkita abonentga aylanadigan MailSender va OrderRepository interfeyslarini yarataylik:
publicinterface MailSender {
void sendConfirmationEmail(Order order);
}
publicinterface OrderRepository {
boolean save(Order order);
}
Endi biz ushbu interfeyslarni bunga tayyor bo'lgan sinflarda qo'llaymiz:
publicclass ConfirmationEmailSender implements MailSender {
@Override
publicvoid sendConfirmationEmail(Order order) {
String name = order.getCustomerName();
String email = order.getCustomerEmail();
// Biz mijozga xat yuboramiz
MySqlConnection connection = new MySqlConnection("database.url");
// buyurtmani ma'lumotlar bazasiga saqlash
return true;
}
}
OrderProcessor sinfimiz aniq tafsilotlarga emas, abstraktsiyalarga bog'liq bo'lishi uchun biz ba'zi tayyorgarlik ishlarini olib bordik. Keling, sinf konstruktoriga bog'liqliklarni kiritish orqali unga o'zgartirish kiritaylik:
private OrderRepository repository;
public OrderProcessor(MailSender mailSender, OrderRepository repository) {
this.mailSender = mailSender;
this.repository = repository;
}
publicvoid process(Order order){
if (order.isValid() && repository.save(order)) {
mailSender.sendConfirmationEmail(order);
}
}
}
Endi bizning sinfimiz konkret dasturlardan ko'ra abstraktsiyalarga bog'liq. Siz o'zingizning xatti-harakatlaringizni OrderProcessor nusxasini yaratishda kerakli bog'liqlikni kiritish orqali osongina o'zgartirishingiz mumkin.
Topshir:
Tanlangan obekt bo’yicha 5 ta SOLID tamoillarini tadbiq etish