Thứ Tư, 8 tháng 5, 2013

Observer

1. Khái niệm

Observer pattern định nghĩa mối quan hệ một - nhiều giữa các đối tượng, theo đó, khi đối tượng chính thay đổi trạng thái thì các đối tượng phụ thuộc sẽ được thông báo cập nhật về sự thay đổi đó.

2. Vấn đề thực tế

Trong thực tế, chúng ta ít nhiều cũng đã từng gặp mô hình quản lý phân cấp, theo đó, 1 nhà quản lý sẽ có nhiều nhân viên cấp dưới. Khi nhà quản lý cần thông báo 1 điều gì đó với cấp dưới, họ sẽ cần các nhân viên cấp dưới tiếp nhận thông báo đó. Trong trường hợp mô hình có thêm giám sát quản lý, thì thông báo cũng cần bên giám sát tiếp nhận.

Như vậy, vấn đề đặt ra ở trường hợp này là làm thế nào để thông báo của nhà quản lý đến được từng nhân viên cấp dưới và đến được bên giám sát? Khi có một thông báo mới, làm thế nào thông báo có thể tự động cập nhật cho các đối tượng trên?

3. Giải pháp

Observer pattern sẽ giúp chúng ta thực hiện được vấn đề nêu trên.

Đầu tiên, chúng ta cần có 1 interface Observable đại diện cho đối tượng quản lý việc thêm, bớt các đối tượng cần tiếp nhận thông điệp. Sau đó, chúng ta tạo thêm 1 interface Observer đại diện cho các đối tượng cần tiếp nhận thông điệp.

Đối tượng quản lý sẽ có một danh sách các đối tượng cần tiếp nhận thông điệp, khi có thông điệp mới, đối tượng quản lý sẽ tiến hành gửi thông điệp cho các đối tượng tiếp nhận nằm trong danh sách đã được định nghĩa trước.

4. Mô hình


5. Code sample

public interface Observer {
    public void updateObserver(String message);
}

public interface Observable {
    public void attach(Observer observer);
    public void detach(Observer observer);
    public void notifyObservers();
}

public class GeneralManager implements Observable{
    String message;
    List<Observer> list = new ArrayList<Observer>();
    
    public void sendMessage(String msg){
        System.out.println("Manager has sent message: " + msg);
        message = msg;
        this.notifyObservers();
    }

    @Override
    public void attach(Observer observer) {
        list.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        if (list.indexOf(observer) >= 0){
            list.remove(observer);
        }
    }

    @Override
    public void notifyObservers() {
        for (Observer o : list){
            o.updateObserver(this.message);
        }
    }
    
}

public class ObserverEmployee implements Observer{
    private String empcode;
    
    public ObserverEmployee(String empid){
        empcode = empid;
    }
    
    @Override
    public void updateObserver(String message) {
        System.out.println("ObserverEmployee "+ empcode + " has got message: "+ message);
    }
    
}

public class ObserverSupervisor implements Observer{
    private String supcode;
    
    public ObserverSupervisor(String supid){
        supcode = supid;
    }
    
    @Override
    public void updateObserver(String message) {
        System.out.println("ObserverSupervisor "+ supcode +" has got message: "+ message);
    }
    
}

public class ObserverPattern {
    public static void main(String[] args){
        GeneralManager manager = new GeneralManager();
        ObserverEmployee emp1 = new ObserverEmployee("emp001");
        ObserverEmployee emp2 = new ObserverEmployee("emp002");
        ObserverSupervisor sup1 = new ObserverSupervisor("sup001");
        ObserverSupervisor sup2 = new ObserverSupervisor("sup002");
        
        manager.attach(emp1);
        manager.attach(emp2);
        manager.attach(sup1);
        manager.attach(sup2);
        
        manager.sendMessage("hi all");
        manager.sendMessage("today is a nice day");  
    }
}

6. Mối liên hệ với các pattern khác

2 nhận xét:

  1. Best free slots online
    Top 10 best slots online in 2021. List of the 강원도 출장마사지 best casino games with real money in 울산광역 출장마사지 2021. Play for 군산 출장샵 free to win real cash prizes and win real What is the most popular slot machine?What 인천광역 출장샵 online slots 영천 출장샵 are the best slots in terms of popularity?

    Trả lờiXóa
  2. This two-hand combination additionally outranks someone hitting 21 with three or more playing cards. A participant can resolve to “split” their playing cards only if the playing cards originally dealt to them are pairs. Splitting turns the pair into two particular person arms, every with their own bet equal to the player’s first bet. The supplier then deals them two extra playing cards to complete every hand and the participant once more has the 검증된 카지노 choices to hit, stand, split, or double down. The real question is whether or not} the purchasers are attracted by the “handheld” games, or are more drawn to blackjack games where they'll pick up and deal with the playing cards. Another debate is whether or not} the face-up delivery process accelerates the game and provides more hand selections.

    Trả lờiXóa