小探设计模式(一)

星期五, 9月 19th, 2008 9:54 下午

简单工厂

使用一个类负责创建其他类的实例,被创建的实例通常都有共同的父类。借War3打个比喻,Archer 和 Huntress都是战争古书训练。AC和Huntress都是战斗单位(兵),都是“兵”的派生类。

打码:

  1. //程序入口
  2. import warunit.*;
  3.  
  4. public class Main {
  5.  
  6. public static void main(String[] args){
  7. AncientOfWar Br=new AncientOfWar();
  8. IWarUnit Ac1=Br.train("Archer");
  9. IWarUnit Ht1=Br.train("Huntress");
  10. Ac1.death();
  11. Ht1.death();
  12. }
  13. }
  14.  
  15. //战斗单位接口
  16. package warunit;
  17.  
  18. public interface IWarUnit {
  19.  
  20. abstract public void born();
  21.  
  22. abstract public void death();
  23. }
  24.  
  25. //AC MM
  26. package warunit;
  27.  
  28. public class Archer implements IWarUnit {
  29.  
  30. public Archer(){
  31. this.born();
  32. }
  33.  
  34. public void born(){
  35. System.out.print("an Archer had been trained\n");
  36. }
  37.  
  38. public void death(){
  39. System.out.print("an Archer had been killed\n");
  40. }
  41. }
  42.  
  43. //Huntress
  44. package warunit;
  45.  
  46. public class Huntress implements IWarUnit {
  47.  
  48. public Huntress(){
  49. this.born();
  50. }
  51.  
  52. public void born(){
  53. System.out.print("an Huntress had been trained\n");
  54. }
  55.  
  56. public void death(){
  57. System.out.print("an Huntress had been killed\n");
  58. }
  59. }
  60.  
  61. //BR
  62. package warunit;
  63.  
  64. public class AncientOfWar {
  65.  
  66. public IWarUnit train(String type){
  67. if(type.equalsIgnoreCase("Archer")){
  68. return new Archer();
  69. }
  70. if(type.equalsIgnoreCase("Huntress")){
  71. return new Huntress();
  72. }
  73. return null;
  74. }
  75. }

发表评论