当前位置:网站首页>常见设置模式(抽象工厂&责任链模式&观察者模式)
常见设置模式(抽象工厂&责任链模式&观察者模式)
2022-06-23 05:16:00 【時宜】
目录
一、 抽象工厂
用于生成指定产品族,一个产品族中包括多种产品。例如:
我们都比较熟悉的电脑制造相关行业,有HP,罗技,联想,戴尔,近几年华为,小米也进来了,每个生产商生产的电脑又包括鼠标,键盘,屏幕等等配件。此时我们需要使用工厂模式来进行管理不同的产品族,这时使用简单工厂(也有叫作工厂方法的)已经无法满足要求,此时可以使用抽象工厂。
类图:

具体代码:
PcFactory(类族)
public abstract class PcFactory {
//制作方法
public abstract Mouse makeMouse();
public abstract Keyboard makeKeyboard();
//为得到具体的工厂的方法服务
private static HpFactory hpFactory = new HpFactory();
private static LogicFactory logicFactory = new LogicFactory();
//为得到具体的工厂的方法服务
public final static int PC_TYPE_HP = 1;
public final static int PC_TYPE_LG = 2;
/**
* 得到具体的工厂的方法
* @param pcType传入表示电脑类型的常数
* @return 返回PcFactory抽象类:面向抽象编程代替面向具体编程
*/
public static PcFactory getPcFactory(int pcType) {
switch (pcType){
case 1:
return hpFactory;
case 2 :
return logicFactory;
default:
return null;
}
}
}HPFactory(惠普)工厂
public class HpFactory extends PcFactory {
//返回抽象类:面向抽象编程代替面向具体编程
@Override
public Mouse makeMouse() {
return new HpMouse();
}
@Override
public Keyboard makeKeyboard() {
return new HpKeyboard();
}
}LogicFactory(罗技)子工厂(继承抽象类PcFactory)
public class LogicFactory extends PcFactory {
@Override
public Mouse makeMouse() {
return new LogicMouse();
}
@Override
public Keyboard makeKeyboard() {
return new LogicKeyboard();
}
}鼠标抽象工厂Keyboard
public abstract class Keyboard {
abstract String getInfo();
}Hpkeyboard(HP的键盘制作工厂)
public class HpKeyboard extends Keyboard {
@Override
String getInfo() {
return "HP keyboard";
}
}LogicKeyboard(Logic的键盘制作工厂)
public class LogicKeyboard extends Keyboard {
@Override
String getInfo() {
return "logic keyboard";
}
}键盘抽象工厂Mouse
public abstract class Mouse {
abstract String getInfo();
}HpMouse(HP的鼠标制作工厂)
public class HpMouse extends Mouse {
@Override
String getInfo() {
return "HP mouse";
}
}LogicMouse (Logic的鼠标制作工厂)
public class LogicMouse extends Mouse {
@Override
String getInfo() {
return "logic mouse";
}
}测试
public class Main {
public static void main(String[] args) {
//通过抽象PcFactory父类得到HP电脑制作工厂
PcFactory HpFactory = PcFactory.getPcFactory(PcFactory.PC_TYPE_HP);
//得到HP制作键盘的方法
Keyboard keyboard = HpFactory.makeKeyboard();
//得到HP制作鼠标的方法
Mouse mouse = HpFactory.makeMouse();
System.out.println(keyboard.getInfo());
System.out.println(mouse.getInfo());
}
}效果如下:

二、 责任链模式
2.1 概念
责任链模式是一个对象的行为模式,很多对象之间形成一条链条,处理请求在这个链条上进行传递,直到责任链的上的某个对象决定处理请求(也可扩展为几个对象处理),这个过程对于用户来说是透明的,也就是说用户并不需要知道是责任链上的哪个对象处理的请求,对请求是否处理由链条上的对象自己决定。
为了便于理解我们可以想象一下击鼓传花的游戏。
2.2 使用场景
web容器中的过滤器算是责任链模式的一个经典场景。另外举个例子:当在论坛上提交内容时,论坛系统需要对一些关键词进行处理,看看有没有包含一些敏感词汇,而这些敏感词汇我们可以使用责任链模式进行处理。
2.3 类图

Filter接口
/**
* Filter接口,实际上是对变化的抽象
* 这种方式会逐个的运行Filter,但不能
* 指定是否需要继续执行后面的Filter。
* 比如:当发现违法了特殊符号的Filter时
* 其后的过滤链没有必要执行
*/
public interface Filter {
void doFilter(Message message);
}CheckSyntaxFiler(对语法结构进行检查)
对语法进行检查不能出现”<>”如果出现了用“#”替换
public class ChackSyntaxFilter implements Filter {
@Override
public void doFilter(Message message) {
String content = message.getContent();
content = content.replace("<", "#");
content = content.replace(">", "#");
message.setContent(content);
}
}WordFilter(敏感词的过滤)
若出现敏感词汇用”***”替换
public class WordFilter implements Filter {
@Override
public void doFilter(Message message) {
String content = message.getContent();
content = content.replace("嘻嘻", "***");
content = content.replace("hha", "***");
message.setContent(content);
}
}
FilterChain(过滤器链)
/**
* 将Filter组织成一个链条
*/
public class FilterChain {
private FilterChain(){}
private static List<Filter> filters = new ArrayList<>();
private static FilterChain instance = new FilterChain();
public static FilterChain getInstance(){
return instance;
}
public FilterChain add(Filter filter) {
filters.add(filter);
return this;
}
public Message dofilters(final Message message) {
for (Filter f : filters) {
f.doFilter(message);
}
return message;
}
}
Message(demo)
package com.zking.patterndemo;
public class Message {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Message{" +
"content='" + content + '\'' +
'}';
}
}
测试
public class Main {
public static void main(String[] args) {
Message msg = new Message();
msg.setContent("hello, <abc>, hhaxx嘻嘻, 哈哈哈");
FilterChain fc = FilterChain.getInstance();
fc.add(new ChackSyntaxFilter())
.add(new WordFilter())
.dofilters(msg);
System.out.println(msg.getContent());
}
}效果如下:
三、观察者模式(Obsever)
3.1 概念
观察者模式是对象的行为模式,有时也称为“发布/订阅模式”或者“监听器模式”。
观察者模式定义了观察者和被观察者之间的一点多的关系,让多个观察者对象可以响应一个被观察者对象。
3.2 使用场景
比较经典的使用场景,比如:java中的swing包中对事件的处理。浏览器对鼠标,键盘等事件的处理等, spring中的事件发布机制也是使用该模式。
3.3 类图

具体代码:
Observer(观察者接口)
public interface Observer {
void bell(BellEvent event);
}Nurse(护士)
public class Nurse implements Observer {
@Override
public void bell(BellEvent event) {
System.out.println("I am nurse, Can I help you?");
}
}Docter(医生)
public class Docter implements Observer {
@Override
public void bell(BellEvent event) {
System.out.println("I am docter, Can I help you?");
}
}Wife(妻子)
public class Wife implements Observer {
@Override
public void bell(BellEvent event) {
System.out.println("baby, I am here, Don't worry !");
}
}Event(总事件)
public abstract class Event {
protected Object source;
public Object getSource() {
return this.source;
}
}BellEvent(事件实现类)
public class BellEvent extends Event {
long timestamp;
public BellEvent(Object source) {
this.timestamp = System.currentTimeMillis();
this.source = source;
}
}Patient(患者)
public class Patient {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void ringBell() {
BellEvent event = new BellEvent(this);
for (Observer observer: observers) {
observer.bell(event);
}
}
}测试
public class Main {
public static void main(String[] args) {
Patient patient = new Patient();
patient.addObserver(new Docter());
patient.addObserver(new Nurse());
patient.addObserver(new Wife());
patient.ringBell();
}
}效果如下:
小结
观察者模式是使用的非常广泛,比如:Listener,Hook,Callback等等,其实都是观察者的一种应用,名称叫法不同而已,思路基本相同。
边栏推荐
- Long substring without repeating characters for leetcode topic resolution
- Skilled use of slicing operations
- vs+qt项目转qt creator
- Remove duplicates from sorted list II of leetcode topic resolution
- A review: neural oscillation and brain stimulation in Alzheimer's disease
- Steam教育对国内大学生的影响力
- How to query fields separated by commas in MySQL as query criteria - find_ in_ Set() function
- 图解 Google V8 # 17:消息队列:V8是怎么实现回调函数的?
- Day_07 传智健康项目-Freemarker
- haas506 2.0开发教程-hota(仅支持2.2以上版本)
猜你喜欢

Jour 04 projet de santé mentale - gestion des rendez - vous - gestion des forfaits

RF content learning

聚焦智慧城市,华为携手中科星图共同开拓数字化新蓝海

Day_ 10 smart health project - permission control, graphic report

Learning Tai Chi Maker - esp8226 (11) distribution network with WiFi manager Library

Introduction to JVM principle

Illustration Google V8 18: asynchronous programming (I): how does V8 implement micro tasks?

开源生态|超实用开源License基础知识扫盲帖(下)

Jour 13 Projet de santé mentale - chapitre 13

Day_ 13 smart health project - Chapter 13
随机推荐
Day_ 08 smart health project - mobile terminal development - physical examination appointment
Coordinate transformation
The softing datafeed OPC suite stores Siemens PLC data in an Oracle Database
CVE-2021-20038
How to add libraries for Arduino ide installation
Leetcode topic resolution single number
Programmers' real ideas | daily anecdotes
Laravel log channel 分组配置
2020 smart power plant industry insight white paper
[DaVinci developer topic] -41-app how SWC reads and writes NVM block data
qt creater搭建osgearth环境(osgQT MSVC2017)
Day_ 01 smart communication health project - project overview and environmental construction
C# wpf 通过绑定实现控件动态加载
Introduction to JVM principle
快速认识 WebAssembly
279.完全平方数
Machine learning 3-ridge regression, Lasso, variable selection technique
Find the number of nodes in the widest layer of a binary tree
There are so many code comments! I laughed
C语言 获取秒、毫秒、微妙、纳秒时间戳

