// Concrete Product A
public class ConcreteProductA implements Product {
@Override
public void use() {
System.out.println("Using ConcreteProductA");
}
}
ConcreteProductB.java
// Concrete Product B
public class ConcreteProductB implements Product {
@Override
public void use() {
System.out.println("Using ConcreteProductB");
}
}
3. Creator.java (Abstract Factory Class)
// Abstract Creator class
public abstract class Creator {
// Factory Method: Must be implemented by concrete creators
public abstract Product factoryMethod();
}
// Concrete Creator A
public class ConcreteCreatorA extends Creator {
@Override
public Product factoryMethod() {
return new ConcreteProductA();
}
}
ConcreteCreatorB.java
// Concrete Creator B
public class ConcreteCreatorB extends Creator {
@Override
public Product factoryMethod() {
return new ConcreteProductB();
}
}
5. Main.java (Client Code)
public class Main {
public static void main(String[] args) {
// Create a factory for ProductA
Creator creatorA = new ConcreteCreatorA();
Product productA = creatorA.factoryMethod();
productA.use(); // Output: Using ConcreteProductA
// Create a factory for ProductB
Creator creatorB = new ConcreteCreatorB();
Product productB = creatorB.factoryMethod();
productB.use(); // Output: Using ConcreteProductB
}
}
🎯 Key Takeaways
✅ Encapsulation: The client does not know which concrete product it gets.
✅ Scalability: Easily add new products and factories.
✅ Decoupling: The factory method isolates the creation logic.
No comments:
Post a Comment