当前位置:网站首页>Common setup modes (Abstract Factory & responsibility chain mode & observer mode)
Common setup modes (Abstract Factory & responsibility chain mode & observer mode)
2022-06-23 06:44:00 【Timely】
Catalog
Two 、 The chain of responsibility model
3、 ... and 、 Observer mode (Obsever)
One 、 Abstract factory
Used to generate the specified product family , A product family includes multiple products . for example :
We are all familiar with computer manufacturing related industries , Yes HP, Logitech , lenovo , Dell , In recent years, Huawei , Xiaomi also came in , Each manufacturer's computer also includes a mouse , keyboard , Screen and other accessories . At this point, we need to use the factory pattern to manage different product families , Use a simple factory ( There is also a method called the factory method ) It has been unable to meet the requirements , You can use an abstract factory at this point .
Class diagram :

Specific code :
PcFactory( etc. )
public abstract class PcFactory {
// Production methods
public abstract Mouse makeMouse();
public abstract Keyboard makeKeyboard();
// For the method of getting specific factory
private static HpFactory hpFactory = new HpFactory();
private static LogicFactory logicFactory = new LogicFactory();
// For the method of getting specific factory
public final static int PC_TYPE_HP = 1;
public final static int PC_TYPE_LG = 2;
/**
* The way to get a specific factory
* @param pcType Pass in a constant that represents the computer type
* @return return PcFactory abstract class : Abstract oriented programming replaces concrete oriented programming
*/
public static PcFactory getPcFactory(int pcType) {
switch (pcType){
case 1:
return hpFactory;
case 2 :
return logicFactory;
default:
return null;
}
}
}HPFactory( HP ) factory
public class HpFactory extends PcFactory {
// Return abstract class : Abstract oriented programming replaces concrete oriented programming
@Override
public Mouse makeMouse() {
return new HpMouse();
}
@Override
public Keyboard makeKeyboard() {
return new HpKeyboard();
}
}LogicFactory( Logitech ) Sub factory ( Inherited abstract class PcFactory)
public class LogicFactory extends PcFactory {
@Override
public Mouse makeMouse() {
return new LogicMouse();
}
@Override
public Keyboard makeKeyboard() {
return new LogicKeyboard();
}
}Mouse Abstract Factory Keyboard
public abstract class Keyboard {
abstract String getInfo();
}Hpkeyboard(HP Keyboard manufacturing factory )
public class HpKeyboard extends Keyboard {
@Override
String getInfo() {
return "HP keyboard";
}
}LogicKeyboard(Logic Keyboard manufacturing factory )
public class LogicKeyboard extends Keyboard {
@Override
String getInfo() {
return "logic keyboard";
}
}Keyboard Abstract Factory Mouse
public abstract class Mouse {
abstract String getInfo();
}HpMouse(HP Mouse manufacturing factory )
public class HpMouse extends Mouse {
@Override
String getInfo() {
return "HP mouse";
}
}LogicMouse (Logic Mouse manufacturing factory )
public class LogicMouse extends Mouse {
@Override
String getInfo() {
return "logic mouse";
}
}test
public class Main {
public static void main(String[] args) {
// By abstraction PcFactory Parent class gets HP Computer manufacturing factory
PcFactory HpFactory = PcFactory.getPcFactory(PcFactory.PC_TYPE_HP);
// obtain HP How to make a keyboard
Keyboard keyboard = HpFactory.makeKeyboard();
// obtain HP How to make a mouse
Mouse mouse = HpFactory.makeMouse();
System.out.println(keyboard.getInfo());
System.out.println(mouse.getInfo());
}
}The effect is as follows :

Two 、 The chain of responsibility model
2.1 Concept
The responsibility chain pattern is the behavior pattern of an object , Many objects form a chain , Processing requests are passed along this chain , Until an object in the chain of responsibility decides to process the request ( It can also be extended to handle several objects ), This process is transparent to users , That is, the user does not need to know which object in the responsibility chain handles the request , It is up to the objects in the chain to decide whether to process the request .
In order to make it easy to understand, we can imagine the game of beating drums and passing flowers .
2.2 Use scenarios
web The filter in the container is a classic scenario of the responsibility chain pattern . Another example : When submitting content on the Forum , The forum system needs to process some keywords , See if there are any sensitive words , We can use the responsibility chain model to deal with these sensitive words .
2.3 Class diagram

Filter Interface
/**
* Filter Interface , It's actually an abstraction of change
* This method will run one by one Filter, But not
* Specify whether to continue with the following Filter.
* such as : When a special symbol is found to be illegal Filter when
* There is no need to execute the following filter chain
*/
public interface Filter {
void doFilter(Message message);
}CheckSyntaxFiler( Check the grammatical structure )
Checking the grammar cannot result in ”<>” If there is a “#” Replace
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( Filter sensitive words )
If sensitive words appear, use ”***” Replace
public class WordFilter implements Filter {
@Override
public void doFilter(Message message) {
String content = message.getContent();
content = content.replace(" Hee hee ", "***");
content = content.replace("hha", "***");
message.setContent(content);
}
}
FilterChain( Filter chain )
/**
* take Filter Organized into a chain
*/
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 + '\'' +
'}';
}
}
test
public class Main {
public static void main(String[] args) {
Message msg = new Message();
msg.setContent("hello, <abc>, hhaxx Hee hee , Ha ha ha ");
FilterChain fc = FilterChain.getInstance();
fc.add(new ChackSyntaxFilter())
.add(new WordFilter())
.dofilters(msg);
System.out.println(msg.getContent());
}
}The effect is as follows :
3、 ... and 、 Observer mode (Obsever)
3.1 Concept
The observer pattern is the behavior pattern of an object , Sometimes it's also called “ Release / A subscription model ” perhaps “ Monitor mode ”.
The observer pattern defines a little more than a relationship between the observer and the observed , Let multiple observer objects respond to one observed object .
3.2 Use scenarios
Classic usage scenarios , such as :java Medium swing Handling of events in the package . Browser to mouse , Handling of keyboard and other events , spring The event publishing mechanism in also uses this pattern .
3.3 Class diagram

Specific code :
Observer( Observer interface )
public interface Observer {
void bell(BellEvent event);
}Nurse( The nurse )
public class Nurse implements Observer {
@Override
public void bell(BellEvent event) {
System.out.println("I am nurse, Can I help you?");
}
}Docter( Doctor )
public class Docter implements Observer {
@Override
public void bell(BellEvent event) {
System.out.println("I am docter, Can I help you?");
}
}Wife( Wife )
public class Wife implements Observer {
@Override
public void bell(BellEvent event) {
System.out.println("baby, I am here, Don't worry !");
}
}Event( Total events )
public abstract class Event {
protected Object source;
public Object getSource() {
return this.source;
}
}BellEvent( Event implementation class )
public class BellEvent extends Event {
long timestamp;
public BellEvent(Object source) {
this.timestamp = System.currentTimeMillis();
this.source = source;
}
}Patient( In patients with )
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);
}
}
}test
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();
}
}The effect is as follows :
Summary
The observer model is widely used , such as :Listener,Hook,Callback wait , In fact, it is an application of the observer , The names are different , The ideas are basically the same .
边栏推荐
- Mysql5.6 (5.7-8) is based on shardingsphere5.1.1 sharding proxy mode. Read / write separation
- haas506 2.0开发教程-高级组件库-modem.voiceCall(仅支持2.2以上版本)
- 如何查看本机IP
- Measurement principle and thickness measurement mode of spectral confocal
- 【踩坑记录】数据库连接未关闭连接,释放资源的坑
- haas506 2.0开发教程-sntp(仅支持2.2以上版本)
- leetcode - 572. A subtree of another tree
- 2022年养老理财产品有哪些?风险小的
- Open source ecology 𞓜 super practical open source license basic knowledge literacy post (Part 2)
- Laravel log channel 分组配置
猜你喜欢

Laravel log channel grouping configuration

常见设置模式(抽象工厂&责任链模式&观察者模式)

解读创客教育中的团结协作精神

二叉树的遍历及相关知识

Haas506 2.0 development tutorial -hota (only supports versions above 2.2)

20220621 Dual Quaternion

redux Actions may not have an undefined “type“ property. Have you misspelled a constant?

bootstrap如何清除浮动的样式

Measurement principle and thickness measurement mode of spectral confocal

Sklearn classification in sklearn_ Report & accuracy / recall /f1 value
随机推荐
关于职业态度
Badly placed ()‘s 问题
c#数据库报错问题大家帮我看看吧
[resolved] "the unity environment took too long to respond. make sure that: \n“
js 动态创建a href 循环下载文件只能下载10个或者固定数目的问题
MySQL ON DUPLICATE KEY 和 PgSQL ON CONFLICT(主键) 处理主键冲突
haas506 2.0开发教程-高级组件库-modem.voiceCall(仅支持2.2以上版本)
嵌入式实时系统线程的副作用
js中if逻辑过多,常见优化
mysql 优化
English grammar_ Adjective comparative - Level 3 change
Leetcode notes: Weekly contest 298
C# wpf 附加属性实现界面上定义装饰器
leetcode - 572. A subtree of another tree
C language obtains second, millisecond, subtle and nanosecond timestamps
Summary of business logic security ideas
Haas506 2.0 development tutorial - Advanced Component Library -modem SMS (only supports versions above 2.2)
2022年养老理财产品有哪些?风险小的
记一次GLIB2.14升级GLIB2.18的记录以及其中的步骤原理
Open source to the world (Part 2): the power of open source from the evolution of database technology BDTC 2021

