设计模式入门--观察者模式

2024-08-24 02:58

本文主要是介绍设计模式入门--观察者模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

概念

当一个主题对象状态发生变化时,则会自动通知它的依赖对象进行一些逻辑的处理,这就是观察者模式。
直白点说,一个类依赖另外一个乃至多个类,这个类实例状态变化时,会调用它所依赖对象的接口,触发它依赖对象进行某些逻辑的处理。专门拿出来感觉很抽象,事实上这个设计模式,我们经常在代码中都会使用到。


角色

  • 抽象主题:被观察者(Subject)。提供对观察者增删、通知等操作接口。

  • 具体主题:具体被观察者。内部提供一个供观察者注册的容器,每个观察者可以有任意多个观察者。当主题对象发生某种变化,会把变化通知给容器中注册的观察者对象。

  • 抽象观察者:Observer,是具体观察者的抽象类或接口,它定义了具体的逻辑处理方法,使得在得到主题更改通知时进行一些逻辑的处理。

  • 具体观察者:抽象观察者的具体实现类。

抽象主题和抽象观察者的意义:利用java的多态性特征,降低具体类与具体类之间的耦合性。


具体代码

1、com.learn.observerpattern.way1(借大佬例子一用)

场景:假设微信用户就是观察者,微信公众号是被观察者,有多个的微信用户关注了某个公众号,当这个公众号更新时就会通知这些订阅的微信用户

抽象主题

package com.learn.observerpattern.way1;/*** 抽象被观察者(Subject)抽象主题对象* Created by chao.du on 2018/2/1.*/
public interface ISubject {/*** 增加订阅者* @param observer*/void addObserver(IObserver observer);/*** 删除订阅者* @param observer*/void delObserver(IObserver observer);/*** 通知订阅者更新消息*/void notifyObserver();/*** 更新状态*/void updateState(String state);
}

具体主题

package com.learn.observerpattern.way1;import java.util.ArrayList;
import java.util.List;/*** 具体主题,被观察者具体实现类* Created by chao.du on 2018/2/1.*/
public class WeixinSubject implements ISubject{private String state;private List<IObserver> observers=new ArrayList<IObserver>();public void addObserver(IObserver observer) {this.observers.add(observer);}public void delObserver(IObserver observer) {this.observers.remove(observer);}public void notifyObserver() {for (IObserver observer:observers){observer.update(this.state);}}public void updateState(String state) {this.state=state;this.notifyObserver();}
}

抽象观察

package com.learn.observerpattern.way1;/*** 观察者接口* Created by chao.du on 2018/2/1.*/
public interface IObserver {public void update(String message);
}

具体观察者

package com.learn.observerpattern.way1;/*** 观察者接口具体观察实现者* Created by chao.du on 2018/2/1.*/
public class WeixinUser implements IObserver {private String name;public WeixinUser(String name) {this.name = name;}public void update(String message) {System.out.println(this.name+"收到了一个通知--"+message);}
}

客户端

package com.learn.observerpattern.way1;/*** 测试客户端* Created by chao.du on 2018/2/1.*/
public class Client {public static void main(String[] args) {//创建微信订阅主题ISubject subject=new WeixinSubject();//给主题添加订阅者subject.addObserver(new WeixinUser("小明"));subject.addObserver(new WeixinUser("小花"));subject.addObserver(new WeixinUser("小美"));//主题更新,通知订阅者subject.updateState("XX微信公众号发布了一篇新文章《如何与dalao同归于尽》");}}

测试结果
这里写图片描述

2、com.learn.observerpattern.way2

场景:资讯网站每天给注册用户推送新闻。抽象主题就是资讯网站,被观察者是注册用户。

抽象主题

package com.learn.observerpattern.way2;/*** 抽象主题* Created by chao.du on 2018/2/1.*/
public interface ISubject {/*** 注册/添加观察者* @param observer*/void addObserver(IObserver observer);/*** 更新主题对象消息状态* @param isGood* @param message*/void updateMessage(boolean isGood,String message);/*** 通知观察者* @param isGood*/void notiryObserver(boolean isGood);}

具体主题

package com.learn.observerpattern.way2;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;/*** 具体主题,具体被观察者* Created by chao.du on 2018/2/1.*/
public class RealSubject implements ISubject {/*** 消息*/private String message;/*** 观察者容器*/private List<IObserver> observerList=new ArrayList<IObserver>();/*** 添加观察者* @param observer*/public void addObserver(IObserver observer){this.observerList.add(observer);}/*** 更新主题对象消息,通知观察者* @param isGood* @param message*/public void updateMessage(boolean isGood,String message) {this.message=message;this.notiryObserver(isGood);}/*** 通知对象,把Message消息对象发送给* @param isGood true好消息 false坏消息*/public void notiryObserver(boolean isGood) {HashMap<String,Object> content=new HashMap<String, Object>();content.put("message",this.message);for (IObserver observer:observerList) {if(isGood){observer.getWeiXinInfo(new Message(Message.MessageType.GOOD,content));}else{observer.getWeiXinInfo(new Message(Message.MessageType.BAD,content));}}}
}

抽象观察者

package com.learn.observerpattern.way2;/*** 抽象观察者* Created by chao.du on 2018/2/1.*/
public interface IObserver {void getWeiXinInfo(Message message);
}

具体观察者1

package com.learn.observerpattern.way2;/*** 具体观察者* Created by chao.du on 2018/2/1.*/
public class RealObserver1 implements IObserver{private String name;public RealObserver1(String name, ISubject weiXinSubject) {this.name=name;weiXinSubject.addObserver(this);}public void getWeiXinInfo(Message message) {System.out.println(this.name+"收到一个"+message.getType().getInfoTip()+"----"+message.getContent().get("message"));}
}

具体观察者2

package com.learn.observerpattern.way2;/*** 具体观察者* Created by chao.du on 2018/2/1.*/
public class RealObserver2 implements IObserver{private String name;public RealObserver2(String name, ISubject weiXinSubject) {this.name=name;weiXinSubject.addObserver(this);}public void getWeiXinInfo(Message message) {System.out.println(this.name+"收到一个"+message.getType().getInfoTip()+"----"+message.getContent().get("message"));}
}

具体观察者3

package com.learn.observerpattern.way2;/*** 具体观察者* Created by chao.du on 2018/2/1.*/
public class RealObserver3 implements IObserver{private String name;public RealObserver3(String name, ISubject weiXinSubject) {this.name=name;weiXinSubject.addObserver(this);}public void getWeiXinInfo(Message message) {System.out.println(this.name+"收到一个"+message.getType().getInfoTip()+"----"+message.getContent().get("message"));}
}

通知消息实体

package com.learn.observerpattern.way2;import java.util.Map;/*** 通知消息实体封装* Created by chao.du on 2018/2/1.*/
public class Message {private  MessageType type;private Map<String,Object> content;public Message(MessageType type, Map<String, Object> content) {this.type = type;this.content = content;}public MessageType getType() {return type;}public void setType(MessageType type) {this.type = type;}public Map<String, Object> getContent() {return content;}public void setContent(Map<String, Object> content) {this.content = content;}enum  MessageType{GOOD(true,"好消息"),BAD(false,"坏消息");private final boolean infoState;private final String infoTip;MessageType(boolean infoState,String infoTip){this.infoState=infoState;this.infoTip=infoTip;}public boolean getInfoState() {return infoState;}public String getInfoTip() {return infoTip;}}
}

客户端

package com.learn.observerpattern.way2;/*** 客户端,测试* Created by chao.du on 2018/2/1.*/
public class Client {public static void main(String[] args) {//创建主题ISubject subject=new RealSubject();//创建观察者,并放入主题集合new RealObserver1("农民",subject);new RealObserver2("教师",subject);new RealObserver3("工人",subject);//主题修改,通知观察者subject.updateMessage(true,"还有几天要放年假了!!!");System.out.println("----------------------------------");subject.updateMessage(false,"过完年房价要涨了!!!");}
}

测试结果
这里写图片描述

github代码


参考资料:
1、《设计模式(三):观察者模式与发布/订阅模式区别》
2、《观察者模式》
3、《 设计模式(五)观察者模式》

这篇关于设计模式入门--观察者模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1101254

相关文章

Linux系统配置NAT网络模式的详细步骤(附图文)

《Linux系统配置NAT网络模式的详细步骤(附图文)》本文详细指导如何在VMware环境下配置NAT网络模式,包括设置主机和虚拟机的IP地址、网关,以及针对Linux和Windows系统的具体步骤,... 目录一、配置NAT网络模式二、设置虚拟机交换机网关2.1 打开虚拟机2.2 管理员授权2.3 设置子

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

SpringBoot如何通过Map实现策略模式

《SpringBoot如何通过Map实现策略模式》策略模式是一种行为设计模式,它允许在运行时选择算法的行为,在Spring框架中,我们可以利用@Resource注解和Map集合来优雅地实现策略模式,这... 目录前言底层机制解析Spring的集合类型自动装配@Resource注解的行为实现原理使用直接使用M

C#原型模式之如何通过克隆对象来优化创建过程

《C#原型模式之如何通过克隆对象来优化创建过程》原型模式是一种创建型设计模式,通过克隆现有对象来创建新对象,避免重复的创建成本和复杂的初始化过程,它适用于对象创建过程复杂、需要大量相似对象或避免重复初... 目录什么是原型模式?原型模式的工作原理C#中如何实现原型模式?1. 定义原型接口2. 实现原型接口3

大数据spark3.5安装部署之local模式详解

《大数据spark3.5安装部署之local模式详解》本文介绍了如何在本地模式下安装和配置Spark,并展示了如何使用SparkShell进行基本的数据处理操作,同时,还介绍了如何通过Spark-su... 目录下载上传解压配置jdk解压配置环境变量启动查看交互操作命令行提交应用spark,一个数据处理框架

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

数论入门整理(updating)

一、gcd lcm 基础中的基础,一般用来处理计算第一步什么的,分数化简之类。 LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } <pre name="code" class="cpp">LL lcm(LL a, LL b){LL c = gcd(a, b);return a / c * b;} 例题: