0

Factory Pattern

Provide an interface to create a related object of a class without exposing the creational logic.

Example – Vehicle Factory – Car, Bus, Truck.

public interface PaymentMethod {
    public void makePayment();
}

class CreditCard implements PaymentMethod {
    public void makePayment() {
        System.out.println("Payment through credit card...");
    }
}

class NetBanking implements PaymentMethod {
    public void makePayment() {
        System.out.println("Payment through net banking...");
    }
}
public interface IPaymentMethodFactory {
    public PaymentMethod getPaymentMethod();
}

class CreditCardFactory implements IPaymentMethodFactory {
    public PaymentMethod getPaymentMethod() {
        return new CreditCard();
    }
}

class NetBankingFactory implements IPaymentMethodFactory {
    public PaymentMethod getPaymentMethod() {
        return new NetBanking();
    }
}

public class FactoryMethodTest {

    public static void main(String[] args) {
        IPaymentMethodFactory factory = new CreditCardFactory();
        PaymentMethod paymentMethod = factory.getPaymentMethod();
        paymentMethod.makePayment();
    }

}

Toufiq Mahmud

Leave a Reply

Your email address will not be published.