Design Pattern Example 4 observer (observer) and iterator (iterator)

Source: Internet
Author: User
The reason for putting these two modes together is the relationship between C # statements. These two modes become easy or different.

Observer (observer)

Class Observer
{
Public Delegate Void Eventhandler (string State );
Public Event eventhandler changeevent;

Public   Void Changestate (string state)
{
If (Changeevent ! =   Null )
{
Changeevent (State );
}
}
}

Call Static   Void Main ( String [] ARGs)
{
Observer obs =   New Observer ();
Obs. changeevent + =   New Observer. eventhandler (obs_changeevent );
Obs. changestate ( " Change " );
Console. Read ();
}

Static   Void Obs_changeevent ( String State)
{
Console. writeline ("I see:" +State );
}

Running result

Iterator (iterator)
Classes that implement the ienumerable and ienumerator interfaces respectivelyPublic   Class Tokens: ienumerable
{
Public   String [] Elements;

Public Tokens ( String Source, Char [] Delimiters)
{
Elements=Source. Split (delimiters );
}

Public Ienumerator getenumerator ()
{
Return NewTokenenumerator (This);
}

}

Public   Class Tokenenumerator: ienumerator
{
Private   Int Position =   - 1 ;
Private Tokens T;

Public Tokenenumerator (tokens T)
{
This. T=T;
}

Public   Bool Movenext ()
{
If (Position < T. elements. Length -   1 )
{
Position++;
Return True;
}
Else
{
Return False;
}
}

Public   Void Reset ()
{
Position= -1;
}

Public   Object Current
{
Get
{
ReturnT. elements [position];
}
}
}

Call Static   Void Main ( String [] ARGs)
{
Tokens =   New Tokens ( " A, B, c " , New   Char [] {','} );
Ienumerator iterator = Tokens. getenumerator ();
While (Iterator. movenext ())
{
String Token = Iterator. Current As   String ;
If (Token ! =   Null )
{
Console. writeline (token );
}
}
Console. Read ();
}

C # generic support makes iterator implementation better.
Result

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.