java 抽象工厂模式 写一个代码
时间: 2023-12-26 12:47:19 浏览: 37
好的,以下是 Java 抽象工厂模式的示例代码:
```
// 创建抽象工厂接口
interface AbstractFactory {
public Product1 createProduct1();
public Product2 createProduct2();
}
// 创建具体工厂1,实现抽象工厂接口
class ConcreteFactory1 implements AbstractFactory {
public Product1 createProduct1() {
return new ConcreteProduct1A();
}
public Product2 createProduct2() {
return new ConcreteProduct2A();
}
}
// 创建具体工厂2,实现抽象工厂接口
class ConcreteFactory2 implements AbstractFactory {
public Product1 createProduct1() {
return new ConcreteProduct1B();
}
public Product2 createProduct2() {
return new ConcreteProduct2B();
}
}
// 创建抽象产品1接口及具体产品1
interface Product1 {}
class ConcreteProduct1A implements Product1 {}
class ConcreteProduct1B implements Product1 {}
// 创建抽象产品2接口及具体产品2
interface Product2 {}
class ConcreteProduct2A implements Product2 {}
class ConcreteProduct2B implements Product2 {}
// 客户端使用抽象工厂接口,无需知道底层实现
class Client {
private Product1 product1;
private Product2 product2;
public Client(AbstractFactory factory) {
this.product1 = factory.createProduct1();
this.product2 = factory.createProduct2();
}
}
```
希望这个示例对您有所帮助。接下来有什么其他问题需要我的帮助吗?
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)