Home Java javaTutorial Java implementation of Observer pattern instance details (picture)

Java implementation of Observer pattern instance details (picture)

Mar 11, 2017 am 11:10 AM

1. Java’s own implementation

Class diagram



##

/**
 * 观察目标 继承自 java.util.Observable
 * @author stone
 *
 */
public class UpdateObservable extends Observable {
	
	private int data;
	
	public UpdateObservable(Observer observer) {
		addObserver(observer);
		/*
		 * add other observer
		 */
	}
	
	public int getData() {
		return data;
	}
	
	public void setData(int data) {
		if (data != this.data) {
			this.data = data;
			setChanged(); //标记 改变, 只有标记后才能通知到
			notifyObservers(); //通知
		}
		
	}

	@Override
	public synchronized void addObserver(Observer o) {
		super.addObserver(o);
	}

	@Override
	public synchronized void deleteObserver(Observer o) {
		super.deleteObserver(o);
	}

	@Override
	public void notifyObservers() {
		super.notifyObservers();
	}

	@Override
	public void notifyObservers(Object arg) {
		super.notifyObservers(arg);
	}

	@Override
	public synchronized void deleteObservers() {
		super.deleteObservers();
	}

	@Override
	protected synchronized void setChanged() {
		super.setChanged();
	}

	@Override
	protected synchronized void clearChanged() {
		super.clearChanged();
	}

	@Override
	public synchronized boolean hasChanged() {
		return super.hasChanged();
	}

	@Override
	public synchronized int countObservers() {
		return super.countObservers();
	}
	
}
Copy after login


/**
 * 观察者	实现 java.util.Observer接口
 * @author stone
 *
 */
public class UpdateObserver implements Observer {

	@Override
	public void update(Observable o, Object arg) {
		System.out.println("接收到数据变化的通知:");
		if (o instanceof UpdateObservable) {
			UpdateObservable uo = (UpdateObservable) o;
			System.out.print("数据变更为:" + uo.getData());
		}
	}

}
Copy after login

2. Customized observation model

Class diagram



/**
 * 抽象观察者	Observer
 * 观察 更新		
 * @author stone
 *
 */
public interface IWatcher {
	/*
	 * 通知接口:
	 * 1. 简单通知
	 * 2. 观察者需要目标的变化的数据,那么可以将目标用作参数, 见Java的Observer和Observable
	 */
//	void update(IWatched watched);
	
	void update();
	
}
Copy after login


/**
 * 抽象目标	Subject
 * 	提供注册和删除观察者对象的接口, 及通知观察者进行观察的接口
 *  及目标 自身被观察的业务的接口
 * @author stone
 *
 */
public interface IWatchedSubject {
	
	public void add(IWatcher watch);

	public void remove(IWatcher watch);
	
	public void notifyWhatchers();
	
	public void update();//被观察业务变化的接口
}
Copy after login


/**
 * 具体观察者		Concrete Observer
 * 
 * @author stone
 *
 */
public class UpdateWatcher implements IWatcher {

	@Override
	public void update() {
		System.out.println(this + "观察到:目标已经更新了");
	}

}
Copy after login


/**
 * 具体目标角色	Concrete Subject
 * @author stone
 *
 */
public class UpdateWatchedSubject implements IWatchedSubject {
	private List<IWatcher> list;
	
	public UpdateWatchedSubject() {
		this.list = new ArrayList<IWatcher>();
	}
	
	@Override
	public void add(IWatcher watch) {
		this.list.add(watch);
	}

	@Override
	public void remove(IWatcher watch) {
		this.list.remove(watch);
	}

	@Override
	public void notifyWhatchers() {
		for (IWatcher watcher : list) {
			watcher.update();
		}
	}
	
	@Override
	public void update() {
		System.out.println("目标更新中....");
		notifyWhatchers();
	}

}
Copy after login

The listener is an implementation of the observer

Class diagram


/**
 * 监听 用户在注册后
 * @author stone
 *
 */
public interface IRegisterListener {
	void onRegistered();
}
Copy after login
/**
 * 监听 当用户登录后
 * @author stone
 *
 */
public interface ILoginListener {
	void onLogined();
}
Copy after login
/*
 * 监听器 是观察者模式的一种实现
 * 一些需要监听的业务接口上添加 监听器,调用监听器的相应方法,实现监听
 */
public class User {
	
	public void register(IRegisterListener register) {
		/*
		 * do ... register
		 */
		System.out.println("正在注册中...");
		//注册后
		register.onRegistered();
	}

	public void login(ILoginListener login) {
		/*
		 * do ... login
		 */
		System.out.println("正在登录中...");
		//登录后
		login.onLogined();
	}

}
Copy after login
/**
 * 观察者(Observer)模式	行为型模式
 *   观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时观察某一个目标对象。
 *   这个目标对象在状态上发生变化时,会通知所有观察者对象,让它们能够自动更新自己
 * 目标对象中需要有添加、移除、通知 观察者的接口
 *   
 * @author stone
 */
public class Test {
	
	public static void main(String[] args) {
		/*
		 * 使用Java自带的Observer接口和Observable类
		 */
		UpdateObservable observable = new UpdateObservable(new UpdateObserver());
		observable.setData(99);
		System.out.println("");
		System.out.println("");
		/*
		 * 自定义的观察者模型
		 */
		IWatchedSubject watched = new UpdateWatchedSubject();
		watched.add(new UpdateWatcher());
		watched.add(new UpdateWatcher());
		watched.update();
		System.out.println("");
		
		/*
		 * 子模式-监听器
		 */
		
		User user = new User();
		user.register(new IRegisterListener() {
			
			@Override
			public void onRegistered() {
				System.out.println("监听到注册后。。。");
			}
		});
		user.login(new ILoginListener() {
			
			@Override
			public void onLogined() {
				System.out.println("监听到登录后。。。");
			}
		});
		
	}
}
Copy after login

Print

接收到数据变化的通知:
数据变更为:99

目标更新中....
observer.UpdateWatcher@457471e0观察到:目标已经更新了
observer.UpdateWatcher@5fe04cbf观察到:目标已经更新了

正在注册中...
监听到注册后。。。
正在登录中...
监听到登录后。。。
Copy after login

The above is the detailed content of Java implementation of Observer pattern instance details (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles