java 抽象工厂模式 例子
时间: 2023-05-19 16:02:31 浏览: 111
java 抽象工厂设计模式 案例
抽象工厂模式是一种创建型设计模式,它提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。下面是一个 Java 抽象工厂模式的例子:
```
public interface AbstractFactory {
public Shape getShape(String shapeType);
}
public class ShapeFactory implements AbstractFactory {
@Override
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
public class FactoryProducer {
public static AbstractFactory getFactory(boolean rounded) {
if (rounded) {
return new RoundedShapeFactory();
} else {
return new ShapeFactory();
}
}
}
public class RoundedShapeFactory implements AbstractFactory {
@Override
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new RoundedCircle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new RoundedRectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new RoundedSquare();
}
return null;
}
}
public class RoundedCircle implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedCircle::draw() method.");
}
}
public class RoundedRectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedRectangle::draw() method.");
}
}
public class RoundedSquare implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedSquare::draw() method.");
}
}
```
在这个例子中,我们定义了一个 `AbstractFactory` 接口和两个实现类 `ShapeFactory` 和 `RoundedShapeFactory`。`ShapeFactory` 用于创建普通形状,而 `RoundedShapeFactory` 用于创建圆角形状。我们还定义了一个 `Shape` 接口和三个实现类 `Circle`、`Rectangle` 和 `Square`,它们分别表示圆形、矩形和正方形。在 `ShapeFactory` 和 `RoundedShapeFactory` 中,我们实现了 `AbstractFactory` 接口中的 `getShape()` 方法,用于创建具体的形状对象。最后,我们定义了一个 `FactoryProducer` 工厂类,用于根据需要返回不同的工厂对象。
阅读全文