Factory Pattern এবং Strategy Pattern হলো দুইটি গুরুত্বপূর্ণ ডিজাইন প্যাটার্ন, যা Apex (Salesforce)-এ কোডের স্থায়িত্ব, রিইউজেবলিটি, এবং মেইনটেনেবিলিটি বৃদ্ধিতে সহায়ক। নিচে এই প্যাটার্নগুলো নিয়ে আলোচনা করা হলো:
Factory Pattern হল একটি Creational Design Pattern, যা ক্লায়েন্টের সাথে সরাসরি কোনো নির্দিষ্ট ক্লাসের উপর নির্ভরশীলতা কমায়। এর মাধ্যমে আমরা একটি Factory Class তৈরি করি, যা নির্দিষ্ট ক্রাইটেরিয়ার ভিত্তিতে বিভিন্ন ধরনের অবজেক্ট তৈরি করে।
ধরুন, আমরা বিভিন্ন ধরনের Notification (যেমন Email, SMS) তৈরি করবো:
public interface Notification {
void send(String message);
}
public class EmailNotification implements Notification {
public void send(String message) {
System.debug('Sending Email: ' + message);
}
}
public class SMSNotification implements Notification {
public void send(String message) {
System.debug('Sending SMS: ' + message);
}
}
public class NotificationFactory {
public static Notification createNotification(String type) {
if (type == 'EMAIL') {
return new EmailNotification();
} else if (type == 'SMS') {
return new SMSNotification();
}
return null;
}
}
// Usage
Notification notification = NotificationFactory.createNotification('EMAIL');
notification.send('Hello!');
Strategy Pattern হলো একটি Behavioral Design Pattern, যা একই কাজের বিভিন্ন অ্যালগরিদমের জন্য ভিন্ন ভিন্ন স্ট্র্যাটেজি (অ্যালগরিদম) আলাদা করে রাখে। এর ফলে আমরা রানটাইমে অ্যালগরিদমগুলো পরিবর্তন করতে পারি।
ধরুন, আমাদের কাছে বিভিন্ন পেমেন্ট মেথড রয়েছে, যেমন CreditCard ও PayPal।
public interface PaymentStrategy {
void pay(Decimal amount);
}
public class CreditCardPayment implements PaymentStrategy {
public void pay(Decimal amount) {
System.debug('Paid ' + amount + ' using Credit Card');
}
}
public class PayPalPayment implements PaymentStrategy {
public void pay(Decimal amount) {
System.debug('Paid ' + amount + ' using PayPal');
}
}
public class PaymentContext {
private PaymentStrategy strategy;
public PaymentContext(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void executePayment(Decimal amount) {
strategy.pay(amount);
}
}
// Usage
PaymentContext context = new PaymentContext(new CreditCardPayment());
context.executePayment(100.00);
context = new PaymentContext(new PayPalPayment());
context.executePayment(200.00);
এই প্যাটার্নগুলো ব্যবহার করে আপনি Apex-এ আপনার কোডের স্থায়িত্ব এবং রিইউজেবলিটি বাড়াতে পারবেন।
common.read_more