Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java осень 2012 лекция 3

167 views

Published on

  • Be the first to comment

  • Be the first to like this

Java осень 2012 лекция 3

  1. 1. Лекция 3. «Message System»
  2. 2. public class Address { static private AtomicInteger abonentIdCreator = new AtomicInteger(); final private int abonentId; public Address(){ this.abonentId = abonentIdCreator.incrementAndGet(); } public int getAbonentId() { return abonentId; } } public interface Abonent { Address getAddress(); }
  3. 3. public abstract class Msg { final private Address from; final private Address to; public Msg(Address from, Address to){ this.from = from; this.to = to; } protected Address getFrom(){ return from; } protected Address getTo(){ return to; } public abstract void exec(Abonent abonent); }
  4. 4. public abstract class MsgToFrontend extends Msg { public MsgToFrontend(Address from, Address to) { super(from, to); } public void exec(Abonent abonent) { if(abonent instanceof Frontend){ exec((Frontend)abonent); } } public abstract void exec(Frontend frontend); }
  5. 5. public class MsgUpdateUserId extends MsgToFrontend { final private int sessionId; final private int userId; public GameInfoMsg(Address from, Address to, int sessionId, int userId) { super(from, to); this. sessionId = sessionId; this. userId = userId; } public void exec(Frontend frontend) { frontend.updateUserId(sessionId, userId); } }
  6. 6. private Map<Address, ArrayBlockingQueue<Msg>> messages = new HashMap<Address, ArrayBlockingQueue<Msg>>(); public void sendMessage(Msg message){ Queue<Msg> messageQueue = messages.get(message.getTo()); messageQueue.add(message); } public void execForAbonent(Abonent abonent) { Queue<Msg> messageQueue = messages.get(abonent.getAddress()); while(!messageQueue.isEmpty()){ Msg message = messageQueue.poll(); message.exec(abonent); } }
  7. 7. public void run() { while (true) { messageSystem.execForAbonent(this); Thread.sleep(TICK_TIME); } }

×