Паттерн: Посетитель (Visitor)
Исходник: Client.java, язык: java [code #537, hits: 8707]
автор: this [добавлен: 10.10.2007]
  1. package visitor;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6.  
  7. public class Client {
  8. static List<Equipment> shop = new ArrayList<Equipment>();
  9.  
  10. /**
  11. * @param args
  12. */
  13. public static void main(String[] args) {
  14.  
  15. FloppyDisk fdisk1 = new FloppyDisk("3.5");
  16. fdisk1.setDisountPrice(8);
  17. fdisk1.setNetPrice(10);
  18. shop.add(fdisk1);
  19.  
  20. Card videoCard1 = new Card("GeForce1");
  21. videoCard1.setDisountPrice(80);
  22. videoCard1.setNetPrice(100);
  23. shop.add(videoCard1);
  24.  
  25. Card videoCard2 = new Card("GeForce2");
  26. videoCard2.setDisountPrice(100);
  27. videoCard2.setNetPrice(120);
  28. shop.add(videoCard2);
  29.  
  30. Card motherCard1 = new Card("Asus");
  31. motherCard1.setDisountPrice(200);
  32. motherCard1.setNetPrice(250);
  33. shop.add(motherCard1);
  34.  
  35. Chassis sys1 = new Chassis("AMD");
  36. FloppyDisk fdisk2 = new FloppyDisk("3.5");
  37. fdisk1.setDisountPrice(9);
  38. fdisk1.setNetPrice(11);
  39. sys1.Add(fdisk2);
  40.  
  41. Card videoCard3 = new Card("GeForce MX");
  42. videoCard3.setDisountPrice(50);
  43. videoCard3.setNetPrice(55);
  44. sys1.Add(videoCard3);
  45.  
  46. Card motherCard2 = new Card("Gigabyte");
  47. motherCard2.setDisountPrice(200);
  48. motherCard2.setNetPrice(250);
  49. sys1.Add(motherCard2);
  50.  
  51. shop.add(sys1);
  52.  
  53. /* ... и т.д. другие товары... */
  54.  
  55. PricingVisitor priceVisitor = new PricingVisitor();
  56. VisitShop(priceVisitor);
  57. System.out.println("Полная стоимость товаров магазина: " +
  58. priceVisitor.getTotal());
  59.  
  60. InventoryVisitor countVisitor = new InventoryVisitor();
  61. VisitShop(countVisitor);
  62. System.out.println("На данный момент магазин располагает:");
  63. System.out.println("Флопиков - " +
  64. countVisitor.getFloppyNum() + " штук,");
  65. System.out.println("Видео и материнских плат - " +
  66. countVisitor.getCardNum() + " штук,");
  67. System.out.println("Системных блоков - " +
  68. countVisitor.getChassisNum() + " штук");
  69.  
  70. }
  71.  
  72. public static void VisitShop(EquipmentVisitor v) {
  73. Iterator<Equipment> assortment = shop.iterator();
  74. while (assortment.hasNext()) {
  75. assortment.next().Accept(v);
  76. }
  77. }
  78.  
  79. }
Реализация, использующая 2 вида посетителей: для расчета суммарной стоимости и количества товара каждого вида.
Тестировалось на: java 1.5.0_04

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