//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : Blacksmith.java
// @ Date : 2016/9/6
// @ Author :
//
//
/**
* The interface containing method for producing objects.
*
*/
public interface Blacksmith {
public Weapon manufactureWeapon(WeaponType type);
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : ElfBlacksmith.java
// @ Date : 2016/9/6
// @ Author :
//
//
/**
* Concrete subclass for creating new objects.
*
*/
public class ElfBlacksmith implements Blacksmith {
public Weapon manufactureWeapon(WeaponType type) {
return new ElfWeapon(type);
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : OrcBlacksmith.java
// @ Date : 2016/9/6
// @ Author :
//
//
/**
* Concrete subclass for creating new objects.
*
*/
public class OrcBlacksmith implements Blacksmith {
public Weapon manufactureWeapon(WeaponType type) {
return new OrcWeapon(type);
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : OrcWeapon.java
// @ Date : 2016/9/6
// @ Author :
//
//
public class OrcWeapon implements Weapon {
private WeaponType weaponType;
public OrcWeapon(WeaponType type) {
weaponType = type;
}
public String toString() {
return "Orcish " + weaponType;
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : ElfWeapon.java
// @ Date : 2016/9/6
// @ Author :
//
//
public class ElfWeapon implements Weapon {
private WeaponType weaponType;
public ElfWeapon(WeaponType weaponType) {
this.weaponType = weaponType;
}
public String toString() {
return "Elven " + weaponType;
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : Weapon.java
// @ Date : 2016/9/6
// @ Author :
//
//
public interface Weapon {
}
public enum WeaponType {
SHORT_SWORD("short sword"),//短刀
SPEAR("spear"),//矛
AXE("axe"),
UNDEFINED("");
private String title;
WeaponType(String title)
{
this.title = title;
}
@Override
public String toString() {
return title;
}
}
/**
* In Factory Method we have an interface (Blacksmith) with a method for
* creating objects (manufactureWeapon).The concrete subclasses (OrcBlacksmith,
* ElfBlacksmith) then override the method to produce objects of their liking.
*
*/
public class App {
public static void main(String[] args) {
Blacksmith blacksmith;
Weapon weapon;
blacksmith = new OrcBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
System.out.println(weapon);
blacksmith = new ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
System.out.println(weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
System.out.println(weapon);
}
}
/*
Orcish spear
Orcish axe
Elven short sword
Elven spear*/
java设计模式进阶_factory-method
最新推荐文章于 2024-08-13 22:29:45 发布