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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles