我正在浏览SO中的“工厂方法”页面并遇到了link。 并且this comment。该示例看起来像一个变体,并且考虑以其原始方式实现:将实例化推迟到子类...
这是我的尝试。以下代码是否实现了链接中指定的示例的Factory模式?请验证并建议是否必须进行任何重新分解。
public class ScheduleTypeFactoryImpl implements ScheduleTypeFactory {
@Override
public IScheduleItem createLinearScheduleItem() {
return new LinearScheduleItem();
}
@Override
public IScheduleItem createVODScheduleItem() {
return new VODScheduleItem();
}
}
public class UseScheduleTypeFactory {
public enum ScheduleTypeEnum {
CableOnDemandScheduleTypeID,
BroadbandScheduleTypeID,
LinearCableScheduleTypeID,
MobileLinearScheduleTypeID
}
public static IScheduleItem getScheduleItem(ScheduleTypeEnum scheduleType) {
IScheduleItem scheduleItem = null;
ScheduleTypeFactory scheduleTypeFactory = new ScheduleTypeFactoryImpl();
switch (scheduleType) {
case CableOnDemandScheduleTypeID:
scheduleItem = scheduleTypeFactory.createVODScheduleItem();
break;
case BroadbandScheduleTypeID:
scheduleItem = scheduleTypeFactory.createVODScheduleItem();
break;
case LinearCableScheduleTypeID:
scheduleItem = scheduleTypeFactory.createLinearScheduleItem();
break;
case MobileLinearScheduleTypeID:
scheduleItem = scheduleTypeFactory.createLinearScheduleItem();
break;
default:
break;
}
return scheduleItem;
}
}
答案 0 :(得分:1)
我认为这是可以的,虽然我认为过于复杂。你真的不需要ScheduleTypeFactoryImpl
课程。然后,您可以将UseScheduleTypeFactory
课程更改为ScheduleTypeFactory
。
我在想的是:
公共类ScheduleTypeFactory {
public enum ScheduleTypeEnum {
CableOnDemandScheduleTypeID,
BroadbandScheduleTypeID,
LinearCableScheduleTypeID,
MobileLinearScheduleTypeID
}
public static IScheduleItem getScheduleItem(ScheduleTypeEnum scheduleType) {
IScheduleItem scheduleItem = null;
switch (scheduleType) {
case CableOnDemandScheduleTypeID:
scheduleItem = new VODScheduleItem();
break;
case BroadbandScheduleTypeID:
scheduleItem = new VODScheduleItem();
break;
case LinearCableScheduleTypeID:
scheduleItem = new LinearScheduleItem();
break;
case MobileLinearScheduleTypeID:
scheduleItem = new LinearScheduleItem();
break;
default:
break;
}
return scheduleItem;
}
}
您可能想要包含“默认”案例。