factory model in java

// 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

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值