什么是工厂模式,实现代码是什么
时间: 2023-12-21 07:03:46 浏览: 31
工厂模式是一种常用的创建型设计模式,它提供一种创建对象的最佳方式,能够为客户端创建对象提供了最佳的解决方案,避免了客户端直接产生对象所带来的不必要的耦合。工厂模式包括简单工厂模式、工厂方法模式和抽象工厂模式等等。实现代码可以参考以下示例:
```
public interface Product {
void show();
}
public class ConcreteProduct1 implements Product {
public void show() {
System.out.println("ConcreteProduct1");
}
}
public class ConcreteProduct2 implements Product {
public void show() {
System.out.println("ConcreteProduct2");
}
}
public class SimpleFactory {
public static Product createProduct(String type) {
if ("product1".equals(type)) {
return new ConcreteProduct1();
} else if ("product2".equals(type)) {
return new ConcreteProduct2();
}
throw new IllegalArgumentException("Invalid product type.");
}
}
public class Client {
public static void main(String[] args) {
Product product1 = SimpleFactory.createProduct("product1");
Product product2 = SimpleFactory.createProduct("product2");
product1.show();
product2.show();
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)