static { ELFARSENAL = new HashMap<>(WeaponType.values().length); Arrays.stream(WeaponType.values()).forEach(type -> ELFARSENAL.put(type, new ElfWeapon(type))); }
@Override public Weapon manufactureWeapon(WeaponType weaponType){ return ELFARSENAL.get(weaponType); }
}
/** * The Factory Method is a creational design pattern which uses factory methods to deal with the * problem of creating objects without specifying the exact class of object that will be created. * This is done by creating objects via calling a factory method either specified in an interface * and implemented by child classes, or implemented in a base class and optionally overridden by * derived classes—rather than by calling a constructor. * * <p>In this Factory Method example we have an interface ({@link Blacksmith}) with a method for * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses ( * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of * their liking. 工厂方法是一种创新性的设计模式,它使用工厂方法来处理创建对象的问题,而无需指定要创建的对象的确切类。 这是通过调用工厂方法创建的对象来完成的,该方法可以在接口中指定并由子类实现,也可以在基类中实现,并有选择地覆盖 派生类-而不是通过调用构造函数。 <p>在此工厂方法示例中,我们具有一个接口({@link Blacksmith}),其中包含用于创建对象的方法({@link Blacksmith#manufactureWeapon})。 具体的子类( {@link OrcBlacksmith},{@ link ElfBlacksmith}),然后重写该方法以生成自己喜欢的对象。 * */ publicclassApp{
privatefinal Blacksmith blacksmith; /** * Creates an instance of <code>App</code> which will use <code>blacksmith</code> to manufacture * the weapons for war. * <code>App</code> is unaware which concrete implementation of {@link Blacksmith} it is using. * The decision of which blacksmith implementation to use may depend on configuration, or * the type of rival in war. * @param blacksmith a non-null implementation of blacksmith */ publicApp(Blacksmith blacksmith){ this.blacksmith = blacksmith; } /** * Program entry point. * * @param args command line args */ publicstaticvoidmain(String[] args){ // Lets go to war with Orc weapons var app = new App(new OrcBlacksmith()); app.manufactureWeapons(); // Lets go to war with Elf weapons app = new App(new ElfBlacksmith()); app.manufactureWeapons(); } privatevoidmanufactureWeapons(){ var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); LOGGER.info(weapon.toString()); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); LOGGER.info(weapon.toString()); } }