设计模式实现:工厂方法与抽象工厂的应用实例
工厂方法(Factory Method)和抽象工厂(Abstract Factory)是面向对象编程中两种常用的工厂模式。
工厂方法(Factory Method)实例:
简单工厂模式:
// 工厂接口
public interface ShapeFactory {
Shape createShape(String shapeType);
}
// 简单工厂实现
class SimpleShapeFactory implements ShapeFactory {
@Override
public Shape createShape(String shapeType) {
if (shapeType.equalsIgnoreCase("Circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("Rectangle")) {
return new Rectangle();
}
return null; //非法形状类型
}
}
// 使用工厂创建形状实例
public class ShapeDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new SimpleShapeFactory();
Shape circle = shapeFactory.createShape("Circle");
if (circle != null) {
System.out.println("Created Circle: " + circle);
}
Shape rectangle = shapeFactory.createShape("Rectangle");
if (rectangle != null) {
System.out.println("Created Rectangle: " + rectangle);
}
}
- 工厂方法的实现,可能在一个具体的类中:
```java
// 具体工厂类
class CircleFactory extends ShapeFactory {
@Override
public Shape createShape(String shapeType) {
}if (shapeType.equalsIgnoreCase("Circle")) {
return new Circle();
}
return null; //非法形状类型
}
// 使用工厂创建具体形状实例
public class ShapeDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new CircleFactory();
Shape circle = shapeFactory.createShape("Circle");
if (circle != null) {
System.out.println("Created Circle: " + circle);
}
// 如果需要创建矩形,可以使用相同工厂
Shape rectangle = shapeFactory.createShape("Rectangle");
if (rectangle != null) {
System.out.println("Created Rectangle: " + rectangle);
}
}
}
**抽象工厂(Abstract Factory)实例:**
1. **多个具体工厂类的集合:**
```java
// 抽象工厂接口
public interface ShapeFactoryInterface {
Shape createShape(String shapeType);
}
// 抽象工厂实现
abstract class AbstractShapeFactory implements ShapeFactoryInterface {
@Override
public Shape createShape(String shapeType) {
// 实现不同形状的具体创建逻辑
if (shapeType.equalsIgnoreCase("Circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("Rectangle")) {
return new Rectangle();
}
return null; //非法形状类型
}
}
使用抽象工厂创建具体形状实例:
// 使用抽象工厂创建具体形状实例
public class ShapeDemo {
public static void main(String[] args) {
ShapeFactoryInterface shapeFactory = new AbstractShapeFactory();
Shape circle = shapeFactory.createShape("Circle");
if (circle != null) {
System.out.println("Created Circle: " + circle);
}
// 创建矩形形状,逻辑同上
Shape rectangle = shapeFactory.createShape("Rectangle");
if (rectangle != null) {
System.out.println("Created Rectangle: " + rectangle);
}
}
}
这样就实现了工厂方法和抽象工厂的设计模式。
还没有评论,来说两句吧...