Observer mode in Java

Source: Internet
Author: User

1. Concept

Defines a one-to-many dependency. When the status of an object changes, all objects dependent on it are notified and automatically updated.

2. UML diagram

3.Code

 Interface Subject
{
Public Void Attach (Observer observer );
Public Void Detach (Observer observer );
Void Yyobservers ();
}

Public Class Concretesubject implements subject
{
Private Vector observersvector = New Vector ();

Public Void Attach (Observer observer ){
Observersvector. addelement (observer );
}

Public Void Detach (Observer observer ){
Observersvector. removeelement (observer );
}

Public Void Yyobservers (){
Enumeration enumeration = observersvector. Clone (). Elements ();
While (Enumeration. hasmoreelements ()){
(Observer) enumeration. nextelement (). Update ();
}
}
}

Public Interface Observer {
Void Update ();
}

Public Class Concreteobserver1 implements observer {
Public Void Update (){
System. Out . Println ( " Obsver1 Execute " );
}
}

Public Class Concreteobserver2 implements observer {
Public Void Update (){
System. Out . Println ( " Obsver2 Execute " );
}
}

Public Class Main {
Public Static Void Main (string [] ARGs ){
Concretesubject = New Concretesubject ();

Concreteobserver1 observer1 = New Concreteobserver1 ();
Concreteobserver2 observer2 = New Concreteobserver2 ();

Generator. addobserver (observer1 );
Generator. addobserver (observer2 );

Concretesubject. policyobservers ();
}
}

4. Application scenarios

When an object needs to be changed at the same time, all objects dependent on it need to be changed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.