抽象工厂模式java代码
时间: 2023-06-23 11:56:06 浏览: 98
以下是一个使用抽象工厂模式的Java代码示例:
首先,我们定义一个抽象工厂接口,它包含了创建产品对象的方法:
```java
public interface AbstractFactory {
public ProductA createProductA();
public ProductB createProductB();
}
```
然后,我们定义两个具体工厂类,它们都实现了抽象工厂接口:
```java
public class ConcreteFactory1 implements AbstractFactory {
public ProductA createProductA() {
return new ConcreteProductA1();
}
public ProductB createProductB() {
return new ConcreteProductB1();
}
}
public class ConcreteFactory2 implements AbstractFactory {
public ProductA createProductA() {
return new ConcreteProductA2();
}
public ProductB createProductB() {
return new ConcreteProductB2();
}
}
```
接下来,我们定义两个抽象产品类,并且定义它们的具体实现:
```java
public interface ProductA {
public void methodA();
}
public interface ProductB {
public void methodB();
}
public class ConcreteProductA1 implements ProductA {
public void methodA() {
System.out.println("ConcreteProductA1.methodA()");
}
}
public class ConcreteProductB1 implements ProductB {
public void methodB() {
System.out.println("ConcreteProductB1.methodB()");
}
}
public class ConcreteProductA2 implements ProductA {
public void methodA() {
System.out.println("ConcreteProductA2.methodA()");
}
}
public class ConcreteProductB2 implements ProductB {
public void methodB() {
System.out.println("ConcreteProductB2.methodB()");
}
}
```
最后,我们可以在客户端代码中使用抽象工厂模式来创建产品对象:
```java
public class Client {
public static void main(String[] args) {
AbstractFactory factory1 = new ConcreteFactory1();
ProductA productA1 = factory1.createProductA();
ProductB productB1 = factory1.createProductB();
productA1.methodA();
productB1.methodB();
AbstractFactory factory2 = new ConcreteFactory2();
ProductA productA2 = factory2.createProductA();
ProductB productB2 = factory2.createProductB();
productA2.methodA();
productB2.methodB();
}
}
```
输出结果:
```
ConcreteProductA1.methodA()
ConcreteProductB1.methodB()
ConcreteProductA2.methodA()
ConcreteProductB2.methodB()
```
阅读全文