静态工厂模式是一种创建型设计模式,通常是通过一个静态方法创建实例对象,而不是通过构造函数直接暴露给客户端。静态工厂模式解决了以下主要问题:
尽管静态工厂模式有很多优点,但它也有一些缺点,如下所述:
总而言之,静态工厂方法是一种非常有用的设计模式,它提供了一种比构造函数更灵活的对象创建机制。它可以让你的代码更加清晰、灵活和易于维护。
public class RGBColor {
private int red;
private int green;
private int blue;
// 私有构造方法,避免外部直接使用new来创建对象
private RGBColor(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
// 静态工厂方法,名称明确表示创建对象的意图
public static RGBColor fromRGB(int red, int green, int blue) {
return new RGBColor(red, green, blue);
}
public static RGBColor fromHex(String hex) {
// 解析hex字符串并创建RGBColor对象
int red = ...
int green = ...
int blue = ...
return new RGBColor(red, green, blue);
}
// ...其他属性和方法
}
public class BooleanWrapper {
private boolean value;
private BooleanWrapper(boolean value) {
this.value = value;
}
private static final BooleanWrapper TRUE = new BooleanWrapper(true);
private static final BooleanWrapper FALSE = new BooleanWrapper(false);
public static BooleanWrapper valueOf(boolean value) {
return value ? TRUE : FALSE;
}
}
public interface Shape {
void draw();
}
public class Circle implements Shape {
public void draw() {
System.out.println("Drawing a circle.");
}
// 静态工厂方法返回接口类型
public static Shape newShape() {
return new Circle();
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Shape shape = Circle.newShape(); // 接口类型指向具体实现类的对象
shape.draw();
}
}
public interface MessageService {
void sendMessage(String message);
}
// 具体实现
public class EmailService implements MessageService {
public void sendMessage(String message) {
System.out.println("Sending email with message: " + message);
}
}
// 工厂类
public class MessagingFactory {
public static MessageService getEmailService() {
return new EmailService();
}
}
// 客户端代码,只关心MessageService接口
public class Client {
public static void main(String[] args) {
MessageService messageService = MessagingFactory.getEmailService();
messageService.sendMessage("Hello World!");
}
}
public enum ShapeType {
CIRCLE,
RECTANGLE
}
public class ShapeFactory {
public static Shape getShape(ShapeType type) {
switch (type) {
case CIRCLE:
return new Circle();
case RECTANGLE:
return new Rectangle();
default:
throw new IllegalArgumentException("Shape type not recognized.");
}
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Shape shape = ShapeFactory.getShape(ShapeType.CIRCLE);
shape.draw(); // 绘制圆形
shape = ShapeFactory.getShape(ShapeType.RECTANGLE);
shape.draw(); // 绘制矩形
}
}