帮我写一个多工厂策略的java代码
时间: 2023-08-22 18:04:29 浏览: 30
好的,以下是一个简单的多工厂策略的Java代码示例:
```
public interface Product {
void print();
}
public class ProductA implements Product {
@Override
public void print() {
System.out.println("This is Product A");
}
}
public class ProductB implements Product {
@Override
public void print() {
System.out.println("This is Product B");
}
}
public interface Factory {
Product createProduct();
}
public class FactoryA implements Factory {
@Override
public Product createProduct() {
return new ProductA();
}
}
public class FactoryB implements Factory {
@Override
public Product createProduct() {
return new ProductB();
}
}
public class Client {
public static void main(String[] args) {
Factory factoryA = new FactoryA();
Product productA = factoryA.createProduct();
productA.print();
Factory factoryB = new FactoryB();
Product productB = factoryB.createProduct();
productB.print();
}
}
```
这个例子中,我们定义了Product接口和两个实现类ProductA和ProductB,以及Factory接口和两个实现类FactoryA和FactoryB。Client类是一个使用多工厂策略的示例,它分别使用FactoryA和FactoryB来创建不同的Product对象,并调用它们的print方法。
这个示例很简单,但可以帮助你了解多工厂策略的基本思想和实现方式。在实际应用中,你可以根据具体的需求和场景来设计和实现多工厂策略。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)