// Interface for the products
interface Product {
void operation();
}
// Concrete products
class ConcreteProduct1 implements Product {
@Override
public void operation() {
System.out.println("Operation of ConcreteProduct1");
}
}
class ConcreteProduct2 implements Product {
@Override
public void operation() {
System.out.println("Operation of ConcreteProduct2");
}
}
// Factory interface
interface Factory {
Product createProduct();
}
// Concrete factory implementations
class ConcreteFactory1 implements Factory {
@Override
public Product createProduct() {
return new ConcreteProduct1();
}
}
class ConcreteFactory2 implements Factory {
@Override
public Product createProduct() {
return new ConcreteProduct2();
}
}
// Client code
public class FactoryExample {
public static void main(String[] args) {
// Creating factory objects
Factory factory1 = new ConcreteFactory1();
Factory factory2 = new ConcreteFactory2();
// Creating products using factories
Product product1 = factory1.createProduct();
Product product2 = factory2.createProduct();
// Using the products
product1.operation();
product2.operation();
}
}
above this example:
- We have an interface
Product
which defines the behavior of different products. - There are concrete implementations of
Product
:ConcreteProduct1
andConcreteProduct2
. - We have a
Factory
interface that declares a method to create products. - Concrete factory classes
ConcreteFactory1
andConcreteFactory2
implement theFactory
interface and provide implementations for creating specific products. - Finally, in the client code, we use these factories to create products without having to instantiate them directly. This provides flexibility, as we can switch between different product implementations without changing the client code.
If this article is helpful to you, please consider making a donation to allow an older programmer to live with more dignity. Scan the QR code to pay 1 cent. thanks very much my friend