当前位置:网站首页>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

One 、 Abstract factory

Two 、 The chain of responsibility model

2.1 Concept

2.2 Use scenarios

2.3 Class diagram

​ edit

3、 ... and 、 Observer mode (Obsever)

3.1 Concept

3.2 Use scenarios

3.3 Class diagram

​ edit

  Summary


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 .

原网站

版权声明
本文为[Timely]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230515485646.html