Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 5–8 Years

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
Chaturmind
← Java Interview Prep: 5–8 Years

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 5–8 YearsJava Design Patterns in Depth
✓ FreeAdvanced· 7 min read

Factory & Abstract Factory Patterns — Interview Questions

Simple factory vs Factory Method vs Abstract Factory, how they differ, implementing each in Java, pros and cons, where a factory genuinely simplifies creation, real Abstract Factory scenarios, and how these patterns support scaling a codebase.

Published September 25, 2026


How to use this lesson

"Factory" means three different things in interviews. Separate them clearly:

  • a simple (static) factory;
  • the GoF Factory Method;
  • the GoF Abstract Factory.

Then show a modern twist: in Spring, a factory is often a map of beans keyed by type.

Q1. What is the Factory pattern, and why is it used so often?

Short answer: A factory encapsulates object creation behind a method, so callers ask for an object by what they need (a type, a key, a configuration), not by which concrete class implements it. It centralises creation logic (validation, caching, choosing an implementation), and lets you add implementations without changing callers.

public final class PaymentGateways {                         // simple (static) factory
    private PaymentGateways() { }
    public static PaymentGateway forCountry(String iso) {
        return switch (iso) {
            case "IN" -> new RazorpayGateway();
            case "US", "GB" -> new StripeGateway();
            default -> throw new IllegalArgumentException("unsupported country " + iso);
        };
    }
}

Key points to cover:

  • JDK examples: List.of, Calendar.getInstance, NumberFormat.getInstance, Executors.newFixedThreadPool, ByteBuffer.allocate.

Learn it in depth → Factory & Abstract Factory

Q2. How does the Factory pattern differ from Abstract Factory?

Short answer:

  • A factory method creates one product, choosing the concrete class.
  • An Abstract Factory is an interface with several creation methods for a family of related products that must be used together, such as a Windows button, checkbox and menu, or an AWS storage, queue and secrets client. Swapping the factory swaps the whole family consistently.

Common trap: "Abstract Factory is a factory of factories". It isn't. It creates a family of products. Concrete factories are often singletons chosen once, not produced by another factory.

Q3. What is the Factory Method, in Java terms?

Short answer: A creator class declares an abstract (or overridable) method that returns a product interface. Subclasses override it to decide the concrete product, while the creator's other methods use the product without knowing its class.

abstract class ReportExporter {
    public final byte[] export(Report r) {                 // template logic, independent of format
        Writer w = createWriter();                          // the factory method
        return w.write(r.rows());
    }
    protected abstract Writer createWriter();
}
class CsvExporter extends ReportExporter { protected Writer createWriter() { return new CsvWriter(); } }
class PdfExporter extends ReportExporter { protected Writer createWriter() { return new PdfWriter(); } }

Key points to cover:

  • In modern Java, the "subclass to choose" part is often replaced by passing a Supplier<Writer> (composition), which gives the same flexibility with less inheritance.

Q4. What are the advantages and disadvantages of factories?

Short answer:

  • Advantages:
    • Decouples callers from concrete classes (depend on abstractions).
    • The Open/Closed principle: add products without changing callers.
    • Centralised, consistent creation: validation, pooling, caching.
    • Easier testing, by injecting a different factory.
  • Disadvantages:
    • Extra indirection and more classes.
    • A central switch factory still changes whenever a product is added. Registration-based factories avoid that.
    • It can hide dependencies, if it's a static global.
    • It's over-engineering when there is only one implementation.

Q5. Give an example where a factory really simplifies object creation.

Short answer: Notification channels. The caller says "notify via SMS", and the factory returns the right sender, already configured with credentials, retry policy and rate limits. In Spring, the most elegant factory is a map of beans: every implementation registers itself, so adding WhatsApp means adding one class, with no factory change.

public interface NotificationSender { Channel channel(); void send(Message m); }

@Component
class NotificationSenderFactory {
    private final Map<Channel, NotificationSender> senders;
    NotificationSenderFactory(List<NotificationSender> all) {           // Spring injects every implementation
        this.senders = all.stream().collect(Collectors.toUnmodifiableMap(NotificationSender::channel, s -> s));
    }
    NotificationSender forChannel(Channel c) {
        return Optional.ofNullable(senders.get(c)).orElseThrow(() -> new UnsupportedChannelException(c));
    }
}

Key points to cover:

  • The source's example of database connections per vendor is real (JDBC's DriverManager and DataSource factories), but today it's usually handled by configuration plus auto-configuration, not hand-written factories.

Q6. What is Abstract Factory, and how does it differ from Factory?

Short answer: Abstract Factory provides an interface for creating families of related objects without naming their concrete classes. The client receives one factory, and gets matching products from it, which guarantees that products from different families are never mixed. A factory method, in contrast, produces a single kind of product.

Q7. Describe a real-world scenario for Abstract Factory.

Short answer:

  • Multi-cloud infrastructure clients: a CloudFactory with storage(), queue() and secrets(). AwsCloudFactory returns S3/SQS/Secrets Manager adapters, and AzureCloudFactory returns Blob Storage, Service Bus and Key Vault adapters. A deployment picks one factory, and every component is consistent.
  • Also:
    • UI toolkits per platform;
    • database dialect families (SQL generator, type mapper, pagination);
    • payment-provider families (charge client, refund client, webhook verifier).

Q8. How do you implement Abstract Factory in Java?

Short answer:

  1. Define product interfaces.
  2. Define a factory interface, with one creation method per product.
  3. Implement one concrete factory per family.
  4. Inject the chosen factory, through configuration or a profile.
public interface Storage { void put(String key, byte[] data); }
public interface MessageQueue { void publish(String topic, String msg); }

public interface CloudFactory {                      // the abstract factory
    Storage storage();
    MessageQueue queue();
}
public final class AwsCloudFactory implements CloudFactory {
    public Storage storage() { return new S3Storage(); }
    public MessageQueue queue() { return new SqsQueue(); }
}
public final class AzureCloudFactory implements CloudFactory {
    public Storage storage() { return new BlobStorage(); }
    public MessageQueue queue() { return new ServiceBusQueue(); }
}

@Configuration
class CloudConfig {
    @Bean @ConditionalOnProperty(name = "cloud.provider", havingValue = "aws")
    CloudFactory aws() { return new AwsCloudFactory(); }
    @Bean @ConditionalOnProperty(name = "cloud.provider", havingValue = "azure")
    CloudFactory azure() { return new AzureCloudFactory(); }
}

Q9. What are the advantages of Abstract Factory?

Short answer:

  • Consistency across related products: no mixing of families.
  • Isolation of concrete classes: clients depend only on interfaces.
  • Easy family swapping, in one place (configuration).
  • Testability, with a fake family for tests (an in-memory storage and queue).
  • It supports inversion of control.

The trade-off: adding a new product kind (say, cache()) means changing the factory interface and every concrete factory. The pattern makes adding families easy, and adding product types hard.

Q10. How does Abstract Factory support scalability in large systems?

Short answer: It scales the codebase and the organisation, rather than runtime throughput:

  • New families (a new cloud, region, tenant tier or partner integration) are added as new classes, without touching existing ones.
  • Teams can own separate families independently.
  • Environment differences are confined to wiring, not scattered if statements.

Combined with DI and configuration, one deployment artifact serves many environments.

Key points to cover:

  • Don't pay the abstraction cost before you have (or clearly expect) a second family. YAGNI applies.

Follow-up questions this topic invites — and their answers

Q: What's the difference between a static factory method and a constructor? A: Static factories have names (Duration.ofSeconds), can return cached instances or subtypes, and can return Optional or null-safe results. Constructors always create a new instance of exactly that class. Effective Java item 1: "Consider static factory methods instead of constructors".

Q: Where does Spring use factories? A: BeanFactory and FactoryBean (for example, LocalContainerEntityManagerFactoryBean), @Bean methods, ObjectProvider, and DataSourceBuilder.

Q: How do you avoid a giant switch in a factory? A: Use registration: implementations declare the key they handle, and the factory builds a Map from them (with Spring collection injection, or ServiceLoader). New implementations need no factory change.

Q: Factory vs Builder? A: A factory decides which object to create, in one call. A builder decides how to assemble one complex object, step by step. They combine well: a factory can return a preconfigured builder.

Previous

Design Patterns Overview & Singleton — Interview Questions

Next

Builder & Prototype Patterns — Interview Questions

AI Tutor

Lesson: Factory & Abstract Factory Patterns — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.