Observer patterns for Android's common design patterns
The observer design pattern is often used in Android applications, and the pattern principle is similar to this scenario:
Users to book newspapers, and then in the newspaper register, the newspaper to statistics users (add users), users can also cancel the subscription, the newspaper delete users; then the user observes the newspaper,
When there is a new newspaper, the newspaper will tell the user and send the newspaper to the user's hand, which, the user is the observer, the newspaper is the Observer, once the newspaper has a new
(data changes) the newspaper will notify the user;
The code examples are as follows:
First of all, according to the common characteristics of users, we have to accept the newspaper, to extract a common user interface
1 /* 2 * user interface 3 * 4 * @author JIAOCG 5 * 6 */ public interface Users { 8 public void receive (); // Accept newspaper method 9 }
Then every user is going to implement this interface, where we create a single user
User A
1 /**2 * User A3 * 4 * @author JIAOCG5 * 6 */7 Public classUserA implements Users {8 9 @OverrideTen Public voidreceive () { One ASystem. out. println ("User A has received"); - - } the -}
User B
1 /**2 * User B3 * 4 * @author JIAOCG5 * 6 */7 Public classUserB implements Users {8 9 @OverrideTen Public voidreceive () { One ASystem. out. println ("User B received a"); - - } the -}
And then we create the Observer newspaper class is primarily responsible for adding deleted users to send newspapers
1 /**2 * By the Observer newspaper3 * 4 * @authorJIAOCG5 * 6 */7 Public classNewspaper {8 PrivateList<users> Users =NewArraylist<users>();9 Ten //Subscribe One Public voidaddUser (Users user) { A users.add (user); - - } the - //Unsubscribe - Public voidremoveuser (Users user) { - users.remove (user); + } - + //transmitter A Public voidSendnewspaper () { at for(Users user:users) { - user.receive (); - } - } - -}
How to use:
1 New newspaper (); 2 newspaper.adduser (new UserA ()); 3 newspaper.adduser (new UserB ()); 4 5 // when you meet your criteria, you start transmitting. 6 newspaper.sendnewspaper ();
Android Common Design Patterns