5.0 KiB
5.0 KiB
工厂模式
目录
工厂模式概念
定义
// 工厂模式:创建对象的模式
// 将对象的创建和使用分离
// 提供统一的创建接口
使用场景
// 1. 需要创建复杂对象
// 2. 需要根据条件创建不同对象
// 3. 需要隐藏对象创建细节
// 4. 需要统一管理对象创建
简单工厂
实现方式
// 简单工厂:一个工厂类创建所有产品
public class ProductFactory {
public static Product createProduct(String type) {
if ("A".equals(type)) {
return new ProductA();
} else if ("B".equals(type)) {
return new ProductB();
}
return null;
}
}
// 使用
Product product = ProductFactory.createProduct("A");
特点
// 优点:
// 1. 实现简单
// 2. 集中管理对象创建
// 缺点:
// 1. 违反开闭原则(添加新产品需要修改工厂类)
// 2. 工厂类职责过重
工厂方法
实现方式
// 工厂方法:每个产品对应一个工厂
// 产品接口
public interface Product {
void use();
}
// 具体产品
public class ProductA implements Product {
@Override
public void use() {
System.out.println("Use ProductA");
}
}
// 工厂接口
public interface ProductFactory {
Product createProduct();
}
// 具体工厂
public class ProductAFactory implements ProductFactory {
@Override
public Product createProduct() {
return new ProductA();
}
}
// 使用
ProductFactory factory = new ProductAFactory();
Product product = factory.createProduct();
特点
// 优点:
// 1. 符合开闭原则
// 2. 每个工厂职责单一
// 3. 易于扩展
// 缺点:
// 1. 类的数量增加
// 2. 增加系统复杂度
抽象工厂
实现方式
// 抽象工厂:创建产品族
// 产品族接口
public interface Button {
void render();
}
public interface Dialog {
void show();
}
// 具体产品族
public class WindowsButton implements Button {
@Override
public void render() {
System.out.println("Windows Button");
}
}
public class WindowsDialog implements Dialog {
@Override
public void show() {
System.out.println("Windows Dialog");
}
}
// 抽象工厂
public interface GUIFactory {
Button createButton();
Dialog createDialog();
}
// 具体工厂
public class WindowsFactory implements GUIFactory {
@Override
public Button createButton() {
return new WindowsButton();
}
@Override
public Dialog createDialog() {
return new WindowsDialog();
}
}
// 使用
GUIFactory factory = new WindowsFactory();
Button button = factory.createButton();
Dialog dialog = factory.createDialog();
特点
// 优点:
// 1. 保证产品族的一致性
// 2. 易于扩展产品族
// 缺点:
// 1. 难以扩展产品种类
// 2. 增加系统复杂度
工厂模式应用
Android 中的应用
// 1. LayoutInflater
View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
// 2. BitmapFactory
Bitmap bitmap = BitmapFactory.decodeFile(path);
// 3. Intent
Intent intent = new Intent(context, MainActivity.class);
实际应用示例
// 网络请求工厂
public class RequestFactory {
public static Request createRequest(String type) {
switch (type) {
case "GET":
return new GetRequest();
case "POST":
return new PostRequest();
default:
return new GetRequest();
}
}
}
工厂模式最佳实践
1. 选择合适的工厂模式
// 简单场景:简单工厂
// 需要扩展:工厂方法
// 需要产品族:抽象工厂
2. 遵循开闭原则
// 对扩展开放,对修改关闭
// 添加新产品时,不需要修改现有代码
3. 使用依赖注入
// 使用依赖注入框架(如 Dagger)
// 更好地管理对象创建
面试常见问题
Q1: 工厂模式的类型?
答案:
- 简单工厂:一个工厂类创建所有产品
- 工厂方法:每个产品对应一个工厂
- 抽象工厂:创建产品族
Q2: 工厂方法的优势?
答案:
- 符合开闭原则
- 每个工厂职责单一
- 易于扩展
Q3: 抽象工厂和工厂方法的区别?
答案:
- 工厂方法:创建单一产品
- 抽象工厂:创建产品族(多个相关产品)
Q4: Android 中的工厂模式应用?
答案:
- LayoutInflater:创建 View
- BitmapFactory:创建 Bitmap
- Intent:创建 Intent 对象
最后更新:2024年