1、先创建抽象层的工厂和对象
public abstract class AbstractFactory {
public abstract EventAbstract createEvent();
public abstract ToolAbstract createTool();
}
public abstract class EventAbstract {
public abstract void occurEvent();
}
public abstract class ToolAbstract {
public abstract void useTool();
}
2、具体工厂和实现类
1、魔法世界
public class MagicFactory extends AbstractFactory {
public EventAbstract createEvent() {
return new MagicEvent();
}
public ToolAbstract createTool() {
return new MagicTool();
}
}
public class MagicEvent extends EventAbstract {
public void occurEvent() {
System.out.println("遇到一只哥布林");
}
}
public class MagicTool extends ToolAbstract {
public void useTool() {
System.out.println("魔法师使用法术球做为工具");
}
}
2、现代世界
public class ModernFactory extends AbstractFactory {
public EventAbstract createEvent() {
return new ModernEvent();
}
public ToolAbstract createTool() {
return new ModernTool();
}
}
public class ModernEvent extends EventAbstract {
public void occurEvent() {
System.out.println("遇到恐怖份子");
}
}
public class ModernTool extends ToolAbstract {
public void useTool() {
System.out.println("现代人使用机枪做为工具");
}
}
3、原始世界
public class OriginalFactory extends AbstractFactory {
public EventAbstract createEvent() {
return new OriginalEvent();
}
public ToolAbstract createTool() {
return new OriginalTool();
}
}
public class OriginalEvent extends EventAbstract {
public void occurEvent() {
System.out.println("遇到一只长毛象");
}
}
public class OriginalTool extends ToolAbstract {
public void useTool() {
System.out.println("原始人使用石矛做为工具");
}
}
执行案例代码
public static void main(String[] args) {
AbstractFactory maFactory = new MagicFactory();
maFactory.createEvent().occurEvent();
maFactory.createTool().useTool();
AbstractFactory moFactory = new ModernFactory();
moFactory.createEvent().occurEvent();
moFactory.createTool().useTool();
AbstractFactory orFactory = new OriginalFactory();
orFactory.createEvent().occurEvent();
orFactory.createTool().useTool();
}
执行效果
|