设计模式快速参考-参观者模式

参观者模式主要对一组固定结构的对象进行访问,一般和组合模式一起使用。

 

abstract class Hardware{
   protected double price;
   protected double getPrice();
   void accept(IComputerVisitor visitor);
}

class Mainboard extends Hardware{
   void accept(IComputerVisitor visitor){
      visitor.visitMainboard(this);
   }
}

class Memory extends Hardware{
   void accept(IComputerVisitor visitor){
      visitor.visitMemory(this);
   }
}

class Display extends Hardware(
   void accept(IComputerVisitor visitor){
      visitor.visitDisplay(this);
   }
}

class NetworkAdapter extends Hardware{
   void accept(IComputerVisitor visitor){
      visitor.visitNetworkAdapter(this);
   }
}

class Computer extends Hardware[
   private List<Hardware> parts = new Arraylist();
   public List<Hardware> add(Hardware hardware){
      parts.add(hardware);
      return parts;
   }
   public void accept(IComputerVisitor visitor){
      for(Hardware h: parts){
         h.accept(visitor);
      }
   }
}

interface IComputerVisitor{
   void visitMainboard(Mainboard mainboard);
   void visitNetworkAdapter(NetworkAdapter adapter);
   void visitDisplay(Display display);
   void visitMemory(Memory memory);
}

//遍历 computer 的每个部件,汇总价格
class PriceVisitor implements IComputerVisitor{
   //总价格
   private double amountPrice;
   void visitMainboard(Mainboard mainboard){
      amountPrice += mainboard.getPrice();
   }
   void visitNetworkAdapter(NetworkAdapter adapter) {
      amountPrice += adapter.getPrice();
   }
   void visitDisplay(Display display) {
      amountPrice += display.getPrice();
   }
   void visitMemory(Memory memory) {
      amountPrice += memory.getPrice();
   }
}


 


Client:

 

Computer computer = new Computer();
Mainboard mainboard = new Mainboard();
NetworkAdapter networkAdapter = new NetworkAdapter();
Display display = new Display();
Memory memory = new Memory();
computer .add(mainboad)
         .add(networkAdapter)
         .add(display)
         .add(memory);
IComputerVisitor visitor = new PriceVisitor();
visitor.accept(computer);
 

 

你可能感兴趣的:(设计模式)