简单工厂模式、工厂方法模式和抽象工厂模式。不同的形式适用于不同的场景。请举例说说各不用的场景
时间: 2023-06-22 10:31:56 浏览: 116
简单工厂模式和抽象工厂模式
好的,我可以举例说明简单工厂模式、工厂方法模式和抽象工厂模式的不同应用场景。
1. 简单工厂模式
简单工厂模式适用于创建对象比较简单的场景,即创建的对象类型比较少,创建过程比较简单,不需要过多的扩展和修改。例如,我们可以使用简单工厂模式来创建图形对象:
```java
public class ShapeFactory {
public static Shape createShape(String shapeType) {
if (shapeType.equalsIgnoreCase("circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("rectangle")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("triangle")) {
return new Triangle();
} else {
return null;
}
}
}
```
2. 工厂方法模式
工厂方法模式适用于创建对象比较复杂的场景,即创建的对象类型比较多,创建过程比较复杂,需要根据不同的对象类型来实现不同的创建过程。例如,我们可以使用工厂方法模式来创建不同类型的日志记录器:
```java
public abstract class Logger {
public abstract void writeLog();
}
public class FileLogger extends Logger {
public void writeLog() {
System.out.println("File logger writes a log record.");
}
}
public class DatabaseLogger extends Logger {
public void writeLog() {
System.out.println("Database logger writes a log record.");
}
}
public interface LoggerFactory {
public Logger createLogger();
}
public class FileLoggerFactory implements LoggerFactory {
public Logger createLogger() {
return new FileLogger();
}
}
public class DatabaseLoggerFactory implements LoggerFactory {
public Logger createLogger() {
return new DatabaseLogger();
}
}
```
3. 抽象工厂模式
抽象工厂模式适用于创建一组相关或相互依赖的对象的场景,即需要创建多个对象,并且这些对象之间有一定的关联和依赖关系。例如,我们可以使用抽象工厂模式来创建不同类型的操作控件和界面控件:
```java
public interface OperationController {
public void control();
}
public interface InterfaceController {
public void display();
}
public class WindowsOperationController implements OperationController {
public void control() {
System.out.println("Windows operation controller controls the operation.");
}
}
public class WindowsInterfaceController implements InterfaceController {
public void display() {
System.out.println("Windows interface controller displays the interface.");
}
}
public class MacOperationController implements OperationController {
public void control() {
System.out.println("Mac operation controller controls the operation.");
}
}
public class MacInterfaceController implements InterfaceController {
public void display() {
System.out.println("Mac interface controller displays the interface.");
}
}
public interface AbstractFactory {
public OperationController createOperationController();
public InterfaceController createInterfaceController();
}
public class WindowsFactory implements AbstractFactory {
public OperationController createOperationController() {
return new WindowsOperationController();
}
public InterfaceController createInterfaceController() {
return new WindowsInterfaceController();
}
}
public class MacFactory implements AbstractFactory {
public OperationController createOperationController() {
return new MacOperationController();
}
public InterfaceController createInterfaceController() {
return new MacInterfaceController();
}
}
```
这样,我们就可以使用抽象工厂模式来创建不同类型的操作控件和界面控件了。
阅读全文