Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

observer pattern

// Java program to demonstrate working of
// onserver pattern
import java.util.ArrayList;
import java.util.Iterator;

// Implemented by Cricket data to communicate
// with observers
interface Subject
{
	public void registerObserver(Observer o);
	public void unregisterObserver(Observer o);
	public void notifyObservers();
}

class CricketData implements Subject
{
	int runs;
	int wickets;
	float overs;
	ArrayList<Observer> observerList;

	public CricketData() {
		observerList = new ArrayList<Observer>();
	}

	@Override
	public void registerObserver(Observer o) {
		observerList.add(o);
	}

	@Override
	public void unregisterObserver(Observer o) {
		observerList.remove(observerList.indexOf(o));
	}

	@Override
	public void notifyObservers()
	{
		for (Iterator<Observer> it =
			observerList.iterator(); it.hasNext();)
		{
			Observer o = it.next();
			o.update(runs,wickets,overs);
		}
	}

	// get latest runs from stadium
	private int getLatestRuns()
	{
		// return 90 for simplicity
		return 90;
	}

	// get latest wickets from stadium
	private int getLatestWickets()
	{
		// return 2 for simplicity
		return 2;
	}

	// get latest overs from stadium
	private float getLatestOvers()
	{
		// return 90 for simplicity
		return (float)10.2;
	}

	// This method is used update displays
	// when data changes
	public void dataChanged()
	{
		//get latest data
		runs = getLatestRuns();
		wickets = getLatestWickets();
		overs = getLatestOvers();

		notifyObservers();
	}
}

// This interface is implemented by all those
// classes that are to be updated whenever there
// is an update from CricketData
interface Observer
{
	public void update(int runs, int wickets,
					float overs);
}

class AverageScoreDisplay implements Observer
{
	private float runRate;
	private int predictedScore;

	public void update(int runs, int wickets,
					float overs)
	{
		this.runRate =(float)runs/overs;
		this.predictedScore = (int)(this.runRate * 50);
		display();
	}

	public void display()
	{
		System.out.println("
Average Score Display: 
"
						+ "Run Rate: " + runRate +
						"
PredictedScore: " +
						predictedScore);
	}
}

class CurrentScoreDisplay implements Observer
{
	private int runs, wickets;
	private float overs;

	public void update(int runs, int wickets,
					float overs)
	{
		this.runs = runs;
		this.wickets = wickets;
		this.overs = overs;
		display();
	}

	public void display()
	{
		System.out.println("
Current Score Display:
"
						+ "Runs: " + runs +
						"
Wickets:" + wickets +
						"
Overs: " + overs );
	}
}

// Driver Class
class Main
{
	public static void main(String args[])
	{
		// create objects for testing
		AverageScoreDisplay averageScoreDisplay =
						new AverageScoreDisplay();
		CurrentScoreDisplay currentScoreDisplay =
						new CurrentScoreDisplay();

		// pass the displays to Cricket data
		CricketData cricketData = new CricketData();

		// register display elements
		cricketData.registerObserver(averageScoreDisplay);
		cricketData.registerObserver(currentScoreDisplay);

		// in real app you would have some logic to
		// call this function when data changes
		cricketData.dataChanged();

		//remove an observer
		cricketData.unregisterObserver(averageScoreDisplay);

		// now only currentScoreDisplay gets the
		// notification
		cricketData.dataChanged();
	}
}
Comment

observer design pattern

import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;

class EventSource {
    public interface Observer {
        void update(String event);
    }
  
    private final List<Observer> observers = new ArrayList<>();
  
    private void notifyObservers(String event) {
        observers.forEach(observer -> observer.update(event));
    }
  
    public void addObserver(Observer observer) {
        observers.add(observer);
    }
  
    public void scanSystemIn() {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            notifyObservers(line);
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: Java List Remove Elements using remove() method 
Java :: MD5 java 
Java :: java add constructor to enum 
Java :: java change hashmap value 
Java :: declaration in java 
Java :: como apanhar caracter de uma string em java 
Java :: array index out of bound exception in java 
Java :: java how to split a string to array 
Java :: next line java does not take input 
Java :: how to use Add Grepper Answer (a) 
Java :: Adding Entire ArrayList to another ArrayList in Java 
Java :: Java Singleton Class Syntax 
Java :: implement queue using array in java 
Java :: java hex to rgb 
Java :: java comparator comparing 
Java :: springboot validator manually validate 
Java :: list of list in java 
Java :: method overloading 
Java :: instanceof java 
Java :: join strings in java 
Java :: Service vs IntentService. 
Java :: Method Overloading by changing the data type of parameters Java 
Java :: gatewayFilters 
Java :: session management in java spring boot for login logut 
Java :: android adb is using too much cpu 
Java :: sum of no 
Java :: iterator java8 
Java :: sysout is not working in eclipse 
Java :: viewresolver in spring boot 
Java :: output of java file in terminal 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =