小探设计模式(二)

星期一, 9月 29th, 2008 9:23 下午

工厂方法

工厂方法把构造产品对象的任务交给子类处理。还是以War3作例。

  1. //IWarFactory.java 工厂父类
  2. package warunit;
  3.  
  4. public interface IWarFactory {
  5.  
  6. public IWarUnit train(String type);
  7. }
  8.  
  9. //AncientOfWar.java 战争古树
  10. package warunit;
  11.  
  12. public class AncientOfWar implements IWarFactory {
  13.  
  14. public IWarUnit train(String type){
  15. if(type.equalsIgnoreCase("Archer")){
  16. return new Archer();
  17. }
  18. if(type.equalsIgnoreCase("Huntress")){
  19. return new Huntress();
  20. }
  21. return null;
  22. }
  23. }
  24.  
  25. //AncientOfWind.java 风之古树
  26. package warunit;
  27.  
  28. public class AncientOfWind implements IWarFactory {
  29.  
  30. public AncientOfWind(){
  31.  
  32. }
  33.  
  34. public IWarUnit train(String type){
  35. if(type.equalsIgnoreCase("hippogryph")){
  36. return new Hippogryph();
  37. }
  38. return null;
  39. }
  40. }
  41.  
  42. //IWarUnit.java 战争单位(兵)父类
  43. package warunit;
  44.  
  45. public interface IWarUnit {
  46.  
  47. abstract public void born();
  48.  
  49. abstract public void death();
  50. }
  51.  
  52. //Archer.java AC MM
  53. package warunit;
  54.  
  55. public class Archer implements IWarUnit {
  56.  
  57. public Archer(){
  58. this.born();
  59. }
  60.  
  61. public void born(){
  62. System.out.print("an Archer had been trained\n");
  63. }
  64.  
  65. public void death(){
  66. System.out.print("an Archer had been killed\n");
  67. }
  68. }
  69.  
  70. //Hippogryph 角鹰
  71. package warunit;
  72.  
  73. public class Hippogryph implements IWarUnit {
  74.  
  75. public Hippogryph(){
  76. this.born();
  77. }
  78.  
  79. public void born(){
  80. System.out.print("A Hippogryph was born");
  81. }
  82.  
  83. public void death(){
  84. System.out.print("A Hippogryph had been killed");
  85. }
  86. }
  87.  
  88. //程序入口
  89. import warunit.*;
  90.  
  91. public class Main {
  92.  
  93. public static void main(String[] args){
  94. AncientOfWar Br=new AncientOfWar();
  95. IWarUnit Ac1=Br.train("Archer");
  96. AncientOfWind Bw=new AncientOfWind();
  97. IWarUnit hp=Bw.train("hippogryph");
  98. Ac1.death();
  99. hp.death();
  100. }
  101. }

发表评论