定义
具有产品制造方法的工厂类,该方法能够根据不同的输入制造输
出不同的产品
public class NoFactoryMain {
public static void main(String[] args) {
TableFan fan = new TableFan();
fan.switchOn();
}
}
class TableFan {
public void switchOn() {
System.out.println("The TableFan is switched on ...");
}
}
问题
- 客户知道类的构造细节,耦合变更问题
- 类名变更
- 参数变更
- 难于优化对象创建流程
- 缓存
简单工厂关系图
定义 风扇 产品接口
public interface IFan {
public void swithOn();
public void switchOff();
}
吊扇的实现
public class CeilingFan implements IFan {
@Override
public void swithOn() {
System.out.println("The CeilingFan is swithed on ...");
}
@Override
public void switchOff() {
System.out.println("The CeilingFan is swithed off ...");
}
}
排风扇的实现
public class ExhaustFan implements IFan {
@Override
public void swithOn() {
System.out.println("The ExhaustFan is swithed on ...");
}
@Override
public void switchOff() {
System.out.println("The ExhaustFan is swithed off ...");
}
}
定义风扇的类型
public enum FanType {
TableFan, //台扇
CeilingFan, //吊扇
ExhaustFan // 排风扇
}
定义 生产风扇的工厂的接口
public interface IFanFactory {
IFan createFan(FanType type);
}
生产风扇工厂的具体实现
public class FanFactory implements IFanFactory {
@Override
public IFan createFan(FanType type) {
switch (type) {
case TableFan:
return new TableFan();
case CeilingFan:
return new CeilingFan();
case ExhaustFan:
return new ExhaustFan();
default:
return new TableFan();
}
}
}
客户端调用
public class SimpleFactoryMain {
public static void main(String[] args) {
IFanFactory simpleFactory = new FanFactory();
// 使用简单工厂创建一个电扇
IFan fan = simpleFactory.createFan(FanType.TableFan);
fan.swithOn();
fan.switchOff();
}
}
好处
- 产品制造流程集中到工厂,客户只和工厂打交道
- 易于变更
- 易于优化
缺点
- 如果扩展需要修改原代码,易出bug