工厂模式
通过将对象的创建过程封装到一个工厂类中,使得客户端不需要直接使用 new
去创建对象,而是通过调用工厂方法来获取所需的对象。这样可以降低代码耦合度,并方便后续的扩展和维护。
示例代码
简单工厂模式(不配合策略模式):
// 手机顶层接口
public interface Phone {
void makeCall(String number);
}
// 华为手机实现
public class HuaweiPhone implements Phone {
@Override
public void makeCall(String number) {
System.out.println("Using HuaweiPhone to call: " + number);
}
}
// 苹果手机实现
public class ApplePhone implements Phone {
@Override
public void makeCall(String number) {
System.out.println("Using ApplePhone to call: " + number);
}
}
// 工厂类
public class PhoneFactory {
public static Phone createPhone(String type) {
switch (type) {
case "Huawei":
return new HuaweiPhone();
case "Apple":
return new ApplePhone();
default:
throw new IllegalArgumentException("Unknown phone type: " + type);
}
}
}
// 测试类
public class Main {
public static void main(String[] args) {
Phone huawei = PhoneFactory.createPhone("Huawei");
huawei.makeCall("123456789");
Phone apple = PhoneFactory.createPhone("Apple");
apple.makeCall("987654321");
}
}
工厂模式 + 策略模式
目的:当需要扩展更多设备(如平板)时,可以抽象顶层接口,将工厂类的职责划分得更清晰。
// 顶层接口:设备
public interface Device {
void start();
}
// 手机实现
public class PhoneDevice implements Device {
@Override
public void start() {
System.out.println("Starting Phone...");
}
}
// 平板实现
public class TabletDevice implements Device {
@Override
public void start() {
System.out.println("Starting Tablet...");
}
}
// 策略模式:设备工厂接口
public interface DeviceFactory {
Device createDevice();
}
// 手机工厂实现
public class PhoneFactory implements DeviceFactory {
@Override
public Device createDevice() {
return new PhoneDevice();
}
}
// 平板工厂实现
public class TabletFactory implements DeviceFactory {
@Override
public Device createDevice() {
return new TabletDevice();
}
}
// 客户端
public class Main {
public static void main(String[] args) {
DeviceFactory phoneFactory = new PhoneFactory();
Device phone = phoneFactory.createDevice();
phone.start();
DeviceFactory tabletFactory = new TabletFactory();
Device tablet = tabletFactory.createDevice();
tablet.start();
}
}
配合 Map
的映射关系
当设备种类较多时,可以用 Map
管理工厂类,动态获取:
import java.util.HashMap;
import java.util.Map;
public class DeviceFactoryRegistry {
private static final Map<String, DeviceFactory> factoryMap = new HashMap<>();
static {
factoryMap.put("Phone", new PhoneFactory());
factoryMap.put("Tablet", new TabletFactory());
}
public static Device getDevice(String type) {
DeviceFactory factory = factoryMap.get(type);
if (factory == null) {
throw new IllegalArgumentException("Unknown device type: " + type);
}
return factory.createDevice();