工厂方法的核心是通过反射方式实例化具体产品类。
举例说明:工厂生产电子设备产品
1:创建抽象工厂:电子产品都有一个开机的功能
public abstract class DeviceBase {
public abstract void start();
}
2:创建具体工厂
- 创建手机工厂
public class PhoneCreateFactory extends CreateDeviceFactory {
@Override
public <T extends DeviceBase> T createDevice(Class<T> tClass) {
PhoneBase phoneBase = null;
String className = tClass.getName();
try {
phoneBase = (PhoneBase) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return (T) phoneBase;
}
}
- 创建电脑工厂
public class ComputerCreateFactory extends CreateDeviceFactory {
@Override
public <T extends DeviceBase> T createDevice(Class<T> tClass) {
ComputerBase computerBase = null;
try {
computerBase = (ComputerBase) Class.forName(tClass.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return (T) computerBase;
}
}
3:定义手机和电脑的基类和实体类
public abstract class DeviceBase {
public abstract void start();
}
public abstract class PhoneBase extends DeviceBase {
public abstract void call(String phoneNumber);
}
public abstract class ComputerBase extends DeviceBase{
}
public class Iphone extends PhoneBase {
@Override
public void call(String phoneNumber) {
System.out.println("This is iphone call:"+phoneNumber);
}
@Override
public void start() {
System.out.println("This is iphone start!");
}
}
public class XiaoMiphone extends PhoneBase {
@Override
public void call(String phoneNumber) {
System.out.println("This is XiaoMi call:"+phoneNumber);
}
@Override
public void start() {
System.out.println("This is XiaoMi start!");
}
}
public class MacComputer extends ComputerBase {
@Override
public void start() {
System.out.println("This is MacComputer!");
}
}
public class ImacComputer extends ComputerBase {
@Override
public void start() {
System.out.println("This is IMacComputer!");
}
}
4:客户端调用工厂方法开始生产设备
public static void main(String arg[]){
CreateDeviceFactory createFactory = new ComputerCreateFactory();
ImacComputer imacComputer = createFactory.createDevice(ImacComputer.class);
imacComputer.start();
MacComputer macComputer = createFactory.createDevice(MacComputer.class);
macComputer.start();
String phoneNumber = "18068409470";
CreateDeviceFactory createDeviceFactory = new PhoneCreateFactory();
Iphone iphone = createDeviceFactory.createDevice(Iphone.class);
iphone.start();
iphone.call(phoneNumber);
XiaoMiphone xiaoMiphone = createDeviceFactory.createDevice(XiaoMiphone.class);
xiaoMiphone.start();
xiaoMiphone.call(phoneNumber);
}