factory model in java

本文介绍了在Java中使用接口和工厂模式实现产品类的灵活性,通过定义Product接口和其具体实现ConcreteProduct,以及Factory接口及其ConcreteFactory实现,展示了如何在客户端代码中动态创建不同产品实例,提高代码的可维护性和扩展性。
// 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 and ConcreteProduct2.
  • We have a Factory interface that declares a method to create products.
  • Concrete factory classes ConcreteFactory1 and ConcreteFactory2 implement the Factory 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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值