Agent pattern design logging module (Java code instance)

Miley shrimp 2022-01-26 10:28:14 阅读数:882

agent pattern design logging module

Catalog

Application scenarios

Agent mode structure view

Example class diagram

Problem solving program code

Program run results


Application scenarios

In an application , You need to record the call date of the business method , Without modifying the existing business class , Provide a journaling agent class for each class , Output the log in the proxy class , For example, in business methods Mehtod() Before calling , Output “Method Method is called , Call time 2021.10.02 05:24:43”, If no exception is thrown after the call, the output is “Mehtod Method call successful ”, Otherwise output “Mehtod Method call failed ”, Calling business methods of real business classes in proxy classes , Design the structure of logging module using agent mode , Draw class diagram and program simulation .

(1) The implementation gives the structure view of agent mode .

(2) The class diagram and code implementation of the example are given .


Agent mode structure view


Example class diagram


Problem solving program code

package test ;
public abstract class Subject {
public abstract void method();
}
//RealSubject:
package test ;
public class RealSubject extends Subject{
@Override
public void method() {
System.out.println("631 Lu Benwei's code ");
}
}
//Proxy:
package test ;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Proxy extends Subject {
private RealSubject realSubject ;
public void before(){
Date now = new Date( );
SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd ',' hh:mm:ss");
System.out.println(" Method method() Called , Call time is :"+ft.format(now));
}
@Override
public void method() {
realSubject = new RealSubject();
before();
try {
realSubject.method();
after();
}catch (NullPointerException e){
System.out.println(" Method method() Call failed ");
}
}
public void after(){
System.out.println(" Method method() Successful call ");
}
}
//Client:
package test ;
public class Client {
public static void main(String[] args) {
Subject subject;
subject = new Proxy();
subject.method();
}
}

Program run results

copyright:author[Miley shrimp],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201261028016964.html