// 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
Productwhich defines the behavior of different products. - There are concrete implementations of
Product:ConcreteProduct1andConcreteProduct2. - We have a
Factoryinterface that declares a method to create products. - Concrete factory classes
ConcreteFactory1andConcreteFactory2implement theFactoryinterface 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

本文介绍了在Java中使用接口和工厂模式实现产品类的灵活性,通过定义Product接口和其具体实现ConcreteProduct,以及Factory接口及其ConcreteFactory实现,展示了如何在客户端代码中动态创建不同产品实例,提高代码的可维护性和扩展性。
1108

被折叠的 条评论
为什么被折叠?



