java观察者设计模式_Java中的观察者设计模式

java观察者设计模式

Observer Pattern is one of the behavioral design pattern. Observer design pattern is useful when you are interested in the state of an object and want to get notified whenever there is any change. In observer pattern, the object that watch on the state of another object are called Observer and the object that is being watched is called Subject.

观察者模式行为设计模式之一 。 当您对对象的状态感兴趣并希望在发生任何更改时得到通知时,观察者设计模式很有用。 在观察者模式中,监视另一个对象状态的对象称为Observer ,而正在监视的对象称为Subject

观察者设计模式 (Observer Design Pattern)

According to GoF, observer design pattern intent is;

根据GoF,观察者设计模式的意图是:

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

在对象之间定义一对多依赖关系,以便当一个对象更改状态时,将自动通知和更新其所有依赖关系。

Subject contains a list of observers to notify of any change in it’s state, so it should provide methods using which observers can register and unregister themselves. Subject also contain a method to notify all the observers of any change and either it can send the update while notifying the observer or it can provide another method to get the update.

主题包含观察者列表,以通知其状态的任何更改,因此它应提供观察者可以自己注册和注销的方法。 主题还包含一种将所有更改通知所有观察者的方法,它既可以在通知观察者的同时发送更新,也可以提供另一种获取更新的方法。

Observer should have a method to set the object to watch and another method that will be used by Subject to notify them of any updates.

观察者应该有一个方法来设置要监视的对象,另一种方法将由Subject用来通知他们任何更新。

Java provides inbuilt platform for implementing Observer pattern through java.util.Observable class and java.util.Observer interface. However it’s not widely used because the implementation is really simple and most of the times we don’t want to end up extending a class just for implementing Observer pattern as java doesn’t provide multiple inheritance in classes.

Java提供了一个内置平台,用于通过java.util.Observable类和java.util.Observer接口实现Observer模式。 但是由于它的实现非常简单,因此并未得到广泛使用,并且大多数时候我们不想只为了实现Observer模式而扩展一个类,因为Java在类中不提供多重继承。

Java Message Service (JMS) uses Observer design pattern along with Mediator pattern to allow applications to subscribe and publish data to other applications.

Java消息服务(JMS)将Observer设计模式Mediator 模式一起使用,以允许应用程序向其他应用程序订阅和发布数据。

Model-View-Controller (MVC) frameworks also use Observer pattern where Model is the Subject and Views are observers that can register to get notified of any change to the model.

模型-视图-控制器(MVC)框架还使用观察者模式,其中模型是主题,视图是观察者,可以注册以获取有关模型的任何更改的通知。

观察者模式Java示例 (Observer Pattern Java Example)

For our observer pattern java program example, we would implement a simple topic and observers can register to this topic. Whenever any new message will be posted to the topic, all the registers observers will be notified and they can consume the message.

对于我们的观察者模式Java程序示例,我们将实现一个简单的主题,观察者可以注册该主题。 每当将任何新消息发布到该主题时,所有注册观察者都会收到通知,他们可以使用该消息。

Based on the requirements of Subject, here is the base Subject interface that defines the contract methods to be implemented by any concrete subject.

根据主题的要求,这里是基本主题接口,用于定义任何具体主题要实施的合同方法。

package com.journaldev.design.observer;

public interface Subject {

	//methods to register and unregister observers
	public void register(Observer obj);
	public void unregister(Observer obj);
	
	//method to notify observers of change
	public void notifyObservers();
	
	//method to get updates from subject
	public Object getUpdate(Observer obj);
	
}

Next we will create contract for Observer, there will be a method to attach the Subject to the observer and another method to be used by Subject to notify of any change.

接下来,我们将为Observer创建合同,将有一种方法将Subject附加到观察者,另一种方法供Subject用来通知任何更改。

package com.journaldev.design.observer;

public interface Observer {
	
	//method to update the observer, used by subject
	public void update();
	
	//attach with subject to observe
	public void setSubject(Subject sub);
}

Now our contract is ready, let’s proceed with the concrete implementation of our topic.

现在我们的合同已经准备好了,让我们继续本主题的具体实施。

package com.journaldev.design.observer;

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

public class MyTopic implements Subject {

	private List<Observer> observers;
	private String message;
	private boolean changed;
	private final Object MUTEX= new Object();
	
	public MyTopic(){
		this.observers=new ArrayList<>();
	}
	@Override
	public void register(Observer obj) {
		if(obj == null) throw new NullPointerException("Null Observer");
		synchronized (MUTEX) {
		if(!observers.contains(obj)) observers.add(obj);
		}
	}

	@Override
	public void unregister(Observer obj) {
		synchronized (MUTEX) {
		observers.remove(obj);
		}
	}

	@Override
	public void notifyObservers() {
		List<Observer> observersLocal = null;
		//synchronization is used to make sure any observer registered after message is received is not notified
		synchronized (MUTEX) {
			if (!changed)
				return;
			observersLocal = new ArrayList<>(this.observers);
			this.changed=false;
		}
		for (Observer obj : observersLocal) {
			obj.update();
		}

	}

	@Override
	public Object getUpdate(Observer obj) {
		return this.message;
	}
	
	//method to post message to the topic
	public void postMessage(String msg){
		System.out.println("Message Posted to Topic:"+msg);
		this.message=msg;
		this.changed=true;
		notifyObservers();
	}

}

The method implementation to register and unregister an observer is very simple, the extra method is postMessage() that will be used by client application to post String message to the topic. Notice the boolean variable to keep track of the change in the state of topic and used in notifying observers. This variable is required so that if there is no update and somebody calls notifyObservers() method, it doesn’t send false notifications to the observers.

注册和注销观察者的方法实现非常简单,额外的方法是postMessage() ,客户端应用程序将使用该方法将String消息发布到主题。 请注意,布尔变量可跟踪主题状态的变化,并用于通知观察者。 此变量是必需的,这样,如果没有更新,并且有人调用notifyObservers()方法,它就不会向观察者发送错误的通知。

Also notice the use of synchronization in notifyObservers() method to make sure the notification is sent only to the observers registered before the message is published to the topic.

还请注意,在notifyObservers()方法中使用了同步 ,以确保仅将消息发送给在将消息发布到主题之前注册的观察者。

Here is the implementation of Observers that will watch over the subject.

这是将监视该主题的Observers的实现。

package com.journaldev.design.observer;

public class MyTopicSubscriber implements Observer {
	
	private String name;
	private Subject topic;
	
	public MyTopicSubscriber(String nm){
		this.name=nm;
	}
	@Override
	public void update() {
		String msg = (String) topic.getUpdate(this);
		if(msg == null){
			System.out.println(name+":: No new message");
		}else
		System.out.println(name+":: Consuming message::"+msg);
	}

	@Override
	public void setSubject(Subject sub) {
		this.topic=sub;
	}

}

Notice the implementation of update() method where it’s calling Subject getUpdate() method to get the message to consume. We could have avoided this call by passing message as argument to update() method.

注意, update()方法的实现是在调用Subject getUpdate()方法来获取消息时使用的。 我们可以通过将message作为参数传递给update()方法来避免此调用。

Here is a simple test program to consume our topic implementation.

这是使用我们的主题实现的简单测试程序。

package com.journaldev.design.observer;

public class ObserverPatternTest {

	public static void main(String[] args) {
		//create subject
		MyTopic topic = new MyTopic();
		
		//create observers
		Observer obj1 = new MyTopicSubscriber("Obj1");
		Observer obj2 = new MyTopicSubscriber("Obj2");
		Observer obj3 = new MyTopicSubscriber("Obj3");
		
		//register observers to the subject
		topic.register(obj1);
		topic.register(obj2);
		topic.register(obj3);
		
		//attach observer to subject
		obj1.setSubject(topic);
		obj2.setSubject(topic);
		obj3.setSubject(topic);
		
		//check if any update is available
		obj1.update();
		
		//now send message to subject
		topic.postMessage("New Message");
	}

}

When we run above program, we get following output.

当我们运行上面的程序时,我们得到以下输出。

Obj1:: No new message
Message Posted to Topic:New Message
Obj1:: Consuming message::New Message
Obj2:: Consuming message::New Message
Obj3:: Consuming message::New Message

Java观察者模式类图 (Java Observer Pattern Class Diagram)

Observer design pattern is also called as publish-subscribe pattern. Some of it’s implementations are;

观察者设计模式也称为发布-订阅模式。 它的一些实现是;

  • java.util.EventListener in Swing

    Swing中的java.util.EventListener
  • javax.servlet.http.HttpSessionBindingListener

    javax.servlet.http.HttpSessionBindingListener
  • javax.servlet.http.HttpSessionAttributeListener

    javax.servlet.http.HttpSessionAttributeListener

That’s all for Observer design pattern in java, I hope you liked it. Share your love with comments and by sharing it with others.

这就是Java中Observer设计模式的全部内容,希望您喜欢它。 通过评论和与他人分享来分享您的爱。

翻译自: https://www.journaldev.com/1739/observer-design-pattern-in-java

java观察者设计模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值