Паттерн: Абстрактная фабрика (Abstract Factory)
Исходник: FleetRun.java, язык: java [code #403, hits: 10886]
автор: this [добавлен: 24.05.2007]
  1. package abstractFactory;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.util.Properties;
  6.  
  7. public class FleetRun {
  8. protected String planFile = "abstractFactory/fleet.properties";
  9. protected Fleet myFleet;
  10. protected Properties plan;
  11.  
  12. public static void main(String[] args) {
  13. FleetRun program = new FleetRun();
  14. // get the fleet plan
  15. try {
  16. program.ReadPlan();
  17. } catch (IOException e) {
  18. System.out.println("Problems with config file: " + program.getPlanFile());
  19. }
  20.  
  21. // create definite factory
  22. FleetFactory factory = program.GetFactory(program.getPlan().getProperty("factory"));
  23.  
  24. // create fleet using created factory
  25. program.CreateFleet(factory);
  26.  
  27. System.out.println(program.getMyFleet());
  28. }
  29.  
  30. public void CreateFleet(FleetFactory factory) {
  31. byte carNum = Byte.parseByte(plan.getProperty("carNum"));
  32. byte truckNum = Byte.parseByte(plan.getProperty("truckNum"));
  33. byte busNum = Byte.parseByte(plan.getProperty("busNum"));
  34.  
  35. myFleet = new Fleet("WWW CarFleet");
  36. String number;
  37.  
  38. // cars >>
  39. for (int i = 1; i <= carNum; i++) {
  40. number = "w00" + i + "ww77rus";
  41. myFleet.AddCar(factory.MakeCar(number));
  42. }
  43.  
  44. // trucks >>
  45. for (int i = 1; i <= truckNum; i++) {
  46. number = "w0" + i + "0ww77rus";
  47. myFleet.AddTruck(factory.MakeTruck(number));
  48. }
  49.  
  50. // buses
  51. for (int i = 1; i <= busNum; i++) {
  52. number = "w00" + i + "ww77rus";
  53. myFleet.AddBus(factory.MakeBus(number));
  54. }
  55. }
  56.  
  57. public Properties ReadPlan() throws IOException {
  58. plan = new Properties();
  59. FileInputStream fin = new FileInputStream(getPlanFile());
  60. plan.load(fin);
  61. fin.close();
  62. return plan;
  63. }
  64.  
  65. public FleetFactory GetFactory(String id) {
  66. if ("ru".equals(id)) {
  67. return new RusFleetFactory();
  68. } else {
  69. return new AmericanFleetFactory();
  70. }
  71. }
  72.  
  73. public Fleet getMyFleet() {
  74. return myFleet;
  75. }
  76.  
  77. public Properties getPlan() {
  78. return plan;
  79. }
  80.  
  81. public String getPlanFile() {
  82. return planFile;
  83. }
  84. }
  85.  
Сущность Client
На основе данных внешнего файла настроек, создает автомобили заданного семейства.
Тестировалось на: java 1.5.0_04

+добавить реализацию