Simple Factory-Factory Method for Design Mode Theme-Abstract Factory-Static Agent-Dynamic Agent

Keywords: JDK Java Spring Programming

1. Factory Mode

1.1 What is factory mode

Separation of creator and caller is implemented, factory mode is divided into simple factory, factory method, abstract factory mode

1.2 Factory Mode Benefits

Factory mode is one of our most common instantiated object modes, replacing the new operation with the factory method.
Using factory mode can reduce program coupling and facilitate later maintenance modifications.
The implementation classes, creation objects, and unified management and control will be selected.This decouples the caller from our implementation class.

1.3 Factory Mode Classification

1.3.1 Simple Factory Mode

Simple factory mode is equivalent to having a variety of products in a factory. Created in a class, customers don't need to know the name of a specific product, they just need to know the parameters corresponding to the product class.However, factories are overburdened and are not conducive to extended maintenance of the system when there are too many types.

public interface Car {
	public void run();
}
public class AoDi implements Car {
	public void run() {
		System.out.println("I'm Audi Car..");
	}
}
public class JiLi implements Car {

	public void run() {
		System.out.println("I'm a Geely car...");
	}
}
public class CarFactory {

	 public static Car createCar(String name) {
		if (StringUtils.isEmpty(name)) {
             return null;
		}
		if(name.equals("Audi")){
			return new AoDi();
		}
		if(name.equals("Auspicious")){
			return new JiLi();
		}
		return null;
	}
}
public class Client01 {

	public static void main(String[] args) {
		Car aodi  =CarFactory.createCar("Audi");
		Car jili  =CarFactory.createCar("Auspicious");
		aodi.run();
		jili.run();
	}

}

Advantages/disadvantages of simple factories
Advantage: Simple factory mode can decide which specific class of objects should be created based on information given by the outside world.A clear distinction between their respective responsibilities and powers is conducive to the optimization of the entire software architecture.

Disadvantages: It is clear that the factory class centralizes the creation logic of all instances and is prone to violate the GRASPR's highly cohesive responsibility allocation principle

1.3.2 Factory Method Mode

What is a factory method pattern

Factory Method mode, also known as polymorphic factory mode.In the factory method mode, the core factory class is no longer responsible for the creation of all products, but gives the specific creation work to the subclass to do.The core class becomes an abstract factory role and is responsible for providing only the interfaces that specific factory subclasses must implement, without touching the details of which product class should be instantiated.

public interface Car {
	public void run();
}
public class AoDi implements Car {
	public void run() {
		System.out.println("I'm Audi Car..");
	}
}
public class JiLi implements Car {

	public void run() {
		System.out.println("I'm a Geely car...");
	}
}
public interface Test02CarFactory {
    public Test02Car createCar();   
}
public class JiLiFactory implements CarFactory {

	public Car createCar() {

		return new JiLi();
	}

}
public class AoDiFactory implements CarFactory {

	public Car createCar() {
	
		return new AoDi();
	}
}
public class Client {

	public static void main(String[] args) {
		Car aodi = new AoDiFactory().createCar();
		Car jili = new JiLiFactory().createCar();
		aodi.run();
		jili.run();
	}

}

1.3.3 Abstract Factory Mode

What is abstract factory mode
An abstract factory is simply a factory of a factory. An abstract factory can create a specific factory from which specific products can be produced.

Engine Interface

//Engine
public interface Engine {

	void run();

	void start();
}

Engine A

class EngineA implements Engine {

	public void run() {	
      System.out.println("Low Allocation Engine!");
	}

	public void start() {
		 System.out.println("Low Matching");
	}

}

Engine B

class EngineB implements Engine {

	public void run() {
      System.out.println("High match, fast turn!");
	}

	public void start() {
		 System.out.println("High Matching");
	}

}

Chair

//Chair
public interface Chair {
	   void run();
}

Seat A

 class ChairA implements Chair{

	public void run() {
		System.out.println("Low Matching");
	}
	
}

Seat B

 class ChairB implements Chair{

	public void run() {
		System.out.println("High Matching");
	}
	
}

Automotive Factory Interface

public interface CarFactory {
	// Create Engine
	Engine createEngine();
	// Create Seats
	Chair createChair();
}

Geely Plant

public class JiLiFactory implements CarFactory  {

	public Engine createEngine() {
	
		return new EngineA();
	}

	public Chair createChair() {
		
		return new ChairA();
	}

}
public class Client002 {
	 public static void main(String[] args) {
		CarFactory carFactory=new JiLiFactory();
		Engine engine=carFactory.createEngine();
		engine.run();
		engine.start();
	}
}

Char and Engine are two product families, CharA and EngineA are of the same product level (both low-grade), CharB and EngineB are of the same product level (both high-grade).

1.3.4 Summary and differences of simple factories, factory methods, Abstract factories

  1. Simple factories are simple to implement. They can be used to produce any product in the same hierarchy by passing in a specific parameter without knowing the class name. The disadvantage of simple factories is that they violate the open and close principle, so expanding and increasing products is not supported.
  2. The factory method and the abstract factory follow the open-close principle and decouple the class relationship.However, the extension is complex and requires a series of additional classes.
  3. It is important to note that the difference between a factory method and an abstract factory is that an abstract factory focuses on a family of products (which can be increased), which is used when there is an associated family of products between product objects, whereas a factory method does not have the concept of a family of products but is used to produce fixed products in the same hierarchy.

2. Agent mode

2.1 What is proxy mode

By controlling access to an object through a proxy, you can access a method of an object in detail, in which processing is invoked or postprocessing is invoked.Both (AOP micro-implementation) and facet-oriented programming are the core technologies of AOP.

2.2 Agent Mode Scenario

SpringAOP, transaction principles, log printing, permission control, remote calls, security agents can conceal real roles

Classification of 2.3 Agents

Static Proxy (Statically Defined Proxy Class)
Dynamic Proxy (dynamic generation of proxy classes)
Jdk comes with dynamic proxy
Cglib, javaassist (Byte Code Operation Library)

2.4 Static Proxy

What is a static proxy:
The source code of the proxy class is created by the programmer or generated by the tool, and then the proxy class is compiled.Static means that byte code files of proxy classes already exist before the program runs, and the relationship between proxy and delegate classes is determined before the program runs.

Static Proxy Code

public interface IUserDao {
	void save();
}
public class UserDao implements IUserDao {
	public void save() {
		System.out.println("Saved data...");
	}
}

proxy class

public class UserDaoProxy implements IUserDao {
	private IUserDao target;

	public UserDaoProxy(IUserDao iuserDao) {
		this.target = iuserDao;
	}

	public void save() {
		System.out.println("Open things...");
		target.save();
		System.out.println("Close things...");
	}

}

Here you can see that the proxy class must implement the interface of the proxy class, which is very detrimental to extension.

2.5 Dynamic Proxy

What is dynamic proxy

  1. Proxy object, no need to implement interface
  2. Proxy object generation is the dynamic building of proxy objects in memory using JDK's API (requires us to specify the type of interface to create proxy objects/target objects)
  3. Dynamic proxy is also called: JDK proxy, interface proxy

2.5.1 JDK Dynamic Proxy

Principle: Proxy classes are created from class loaders and interfaces (this proxy class is an implementation class of interfaces, so you must use interfaces to generate proxies for interfaces, under the java.lang.reflect package)

Implementation: Create your own call processor IvocationHandler handler by implementing the InvocationHandler interface = new InvocationHandlerImpl (...;
Create a dynamic proxy class by specifying a ClassLoader object and a set of interface s for the Proxy class
Class clazz = Proxy.getProxyClass(classLoader,new Class[]{...});
Gets the constructor of the dynamic proxy class through the reflection mechanism, whose parameter type is to call the processor interface type Constructor constructor = clazz.getConstructor(newClass[]InvocationHandler.class});
Create an instance of the proxy class through the constructor, passing in the calling processor object as an argument to Interface Proxy = (Interface)constructor.newInstance(new Object[] (handler));

Disadvantages: jdk dynamic proxy, must be interface-oriented, target business class must implement interface

// Call processor object implementing InvocationHandler interface each time a dynamic proxy class object is generated 
public class InvocationHandlerImpl implements InvocationHandler {
	private Object target;// This is actually a business implementation class object used to call specific business methods
	// Pass in target object through constructor
	public InvocationHandlerImpl(Object target) {
		this.target = target;
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;
		System.out.println("Call start processing");
		result = method.invoke(target, args);
		System.out.println("Call End Processing");
		return result;
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// Proxy Object
		IUserDao userDao = new UserDao();
		InvocationHandlerImpl invocationHandlerImpl = new InvocationHandlerImpl(userDao);
		ClassLoader loader = userDao.getClass().getClassLoader();
		Class<?>[] interfaces = userDao.getClass().getInterfaces();
		// Primary loader, set of interfaces, and call handling dynamic proxy instances
		IUserDao newProxyInstance = (IUserDao) Proxy.newProxyInstance(loader, interfaces, invocationHandlerImpl);
		newProxyInstance.save();
	}

}

2.5.2 CGLIB Dynamic Proxy

Principle: The class file of the proxy object class is loaded using the asm open source package and processed by modifying its byte code to generate a subclass.

What is CGLIB dynamic proxy
Using cglib[Code Generation Library] to implement dynamic proxy does not require a delegate class to implement an interface. The bottom level uses the asm byte code generation framework to generate the byte code of the proxy class

CGLIB dynamic proxy related code:

public class CglibProxy implements MethodInterceptor {
	private Object targetObject;
	// If the target type here is Object, any parameter can be accepted as the proxy class to implement dynamic proxy
	public Object getInstance(Object target) {
		// Set classes that need to create subclasses
		this.targetObject = target;
		//Generate virtual subclasses of target proxy objects
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(target.getClass());
		enhancer.setCallback(this);
		return enhancer.create();
	}

	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		System.out.println("Open things");
		Object result = proxy.invoke(targetObject, args);
		System.out.println("Close things");
		// Return Proxy Object
		return result;	
	}
	public static void main(String[] args) {
		CglibProxy cglibProxy = new CglibProxy();
		UserDao userDao = (UserDao) cglibProxy.getInstance(new UserDao());	
		userDao.save();
	}
}

2.5.3 CGLIB Dynamic Proxy and JDK Dynamic Difference

The java dynamic proxy uses reflection to generate an anonymous class that implements the proxy interface and calls InvokeHandler to process it before calling a specific method.
The cglib dynamic proxy uses the asm open source package to load the class file of the proxy object class and to generate subclasses by modifying its byte code.

In Spring:
1. If the target object implements the interface, the dynamic proxy of JDK will be used by default to implement AOP
2. If the target object implements the interface, you can force CGLIB to implement AOP
3. If the target object does not implement the interface, the CGLIB library must be used. spring will automatically convert between the JDK dynamic proxy and the CGLIB

The JDK dynamic proxy can only generate proxies for classes that implement interfaces, not for classes.
CGLIB implements proxies for classes, mainly by generating a virtual subclass of a specified class that overrides the methods in it.
Since it is inheritance, it is best not to declare the target proxy class or method as final, because final prevents inheritance and polymorphism, otherwise the following errors will occur:

106 original articles published. 29% praised. 10,000 visits+
Private letter follow

Posted by patrickm on Tue, 03 Mar 2020 18:48:06 -0800