Question: Modify the program in the Publish/Subscribe design pattern tutorial so that three subscriber objects are notified of changes when the count variable is three or

Modify the program in the Publish/Subscribe design pattern tutorial so that three subscriber objects are notified of changes when the count variable is three or greater. Each subscriber object should display a customized message that reads Subscriber x has been notified, where x will be 1, 2, or 3.

PLZ USE BELOW CODES

Heres some sample code to illustrate this pattern:

public class Publisher { private Subscriber [] subscriberList; // An array stores subscribers private int maximumSubscribers; // Maximum number of subscribers private int nextIndex; // Array index of next subscriber public Publisher( int max ) { // Initialize attributes & create subscriber array maximumSubscribers = max; subscriberList = new subscriber[ maximumSubscribers ]; nextIndex = 0; } public void register( Subscriber s ) { // Register a subscriber unless the subscriber array is full if ( nextIndex < maximumSubscribers ) subscriberList[ nextIndex++ ] = s; else System.out.println( "ERROR: Subscriber List is full" ); } public void notifySubscribers() { // Iterate through the subscriber array & invoke update() methods for ( int i = 0; i < nextIndex; i++ ) subscriberList[ i ].update(); } } Heres some sample code for the Subscriber class.
public class Subscriber { public void update() { } }
Heres some code for the MyPublisher class. public class MyPublisher extends Publisher { private int count; public MyPublisher( int mx ) { super( mx ); count = 0; } public void increment() { count++; //Notify subscribers if count >= 3 if ( count >= 3 ) notifySubscribers(); } }

Heres some code for the MySubscriber class. It overrides the inherited update() method so that a message will be displayed when its update() method is invoked.

public class MySubscriber extends Subscriber { public void update() { System.out.println( "Notified of state change" ); } } 

Now, well write a program to test things out.

public class TestPattern { public static void main( String [] args ) { // Create Publisher & Subscriber objects MySubscriber aSubscriber = new MySubscriber(); MyPublisher aPublisher = new MyPublisher( 2 ); // Register a Subscriber aPublisher.register( aSubscriber ); // Increment Publisher object to cause state changes aPublisher.incrememnt(); aPublisher.incrememnt(); aPublisher.incrememnt(); aPublisher.incrememnt(); } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!