java 抽象工厂模式代码
时间: 2023-09-26 17:11:06 浏览: 70
下面是一个简单的 Java 抽象工厂模式的代码示例:
首先,定义一个抽象工厂接口:
```java
public interface AbstractFactory {
Shape createShape();
Color createColor();
}
```
然后,定义两个具体的工厂类实现抽象工厂接口:
```java
public class RectangleFactory implements AbstractFactory {
@Override
public Shape createShape() {
return new Rectangle();
}
@Override
public Color createColor() {
return new RedColor();
}
}
public class CircleFactory implements AbstractFactory {
@Override
public Shape createShape() {
return new Circle();
}
@Override
public Color createColor() {
return new BlueColor();
}
}
```
接下来,定义产品接口 Shape 和 Color:
```java
public interface Shape {
void draw();
}
public interface Color {
void fill();
}
```
再定义两个具体的产品类实现产品接口:
```java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class RedColor implements Color {
@Override
public void fill() {
System.out.println("Inside RedColor::fill() method.");
}
}
public class BlueColor implements Color {
@Override
public void fill() {
System.out.println("Inside BlueColor::fill() method.");
}
}
```
最后,客户端可以使用抽象工厂来创建产品:
```java
public class Client {
public static void main(String[] args) {
AbstractFactory factory1 = new RectangleFactory();
Shape shape1 = factory1.createShape();
Color color1 = factory1.createColor();
shape1.draw();
color1.fill();
AbstractFactory factory2 = new CircleFactory();
Shape shape2 = factory2.createShape();
Color color2 = factory2.createColor();
shape2.draw();
color2.fill();
}
}
```
输出结果为:
```
Inside Rectangle::draw() method.
Inside RedColor::fill() method.
Inside Circle::draw() method.
Inside BlueColor::fill() method.
```
阅读全文