In Factory Design Pattern we create an object without exposing the object creation and initialization logic to the client and client will refer to the newly created object using a common interface
The Factory pattern is a creational design pattern that provides an interface for creating objects without specifying their exact classes. It encapsulates object creation logic and returns objects through a common interface.
This implementation demonstrates a credit card system where different types of credit cards are created based on client requirements:
- ICreditCard Interface: Common interface for all credit card types
- CreditCardFactory: Factory class that creates appropriate credit card objects
- Concrete Products: MoneyBack, Platinum, and Titanium credit card implementations
ICreditCard- Product interface defining GetCardType(), GetCreditLimit(), and GetAnnualCharge() methodsCreditCardFactory- Factory class with static GetCreditCard() methodMoneyBack- Concrete product with basic features (₹1500 limit, ₹500 annual charge)Platinum- Concrete product with premium features (₹35000 limit, ₹2000 annual charge)Titanium- Concrete product with mid-tier features (₹25000 limit, ₹1500 annual charge)
ICreditCard cardDetails = CreditCardFactory.GetCreditCard("Platinum");
if (cardDetails != null)
{
Console.WriteLine("CardType: " + cardDetails.GetCardType()); // "Platinum Plus"
Console.WriteLine("CreditLimit: " + cardDetails.GetCreditLimit()); // 35000
Console.WriteLine("AnnualCharge: " + cardDetails.GetAnnualCharge()); // 2000
}- Encapsulates object creation logic in one place
- Client code doesn't need to know about concrete classes
- Easy to add new credit card types without modifying existing code
- Follows Single Responsibility Principle
- Reduces coupling between client and concrete classes