Factory mode and agency mode

Factory mode

   The factory pattern is one of the most commonly used design patterns in java. This type of design pattern belongs to the creation pattern, which provides developers with the best pattern for creating objects in theory.
   In use, the developer only needs to tell it to implement which interface, and the factory pattern dynamically creates an implementation class for the developer. This pattern is called a dynamic proxy.

Factory mode and agency mode

   In using the Spring framework, it is actually to use IOC/Di and AOP, aspect-oriented programming, these two can be said to be the soul of Spring.

The factory model can be divided into three categories

   1. Simple Factory Mode (Simple Factory) is an abstract class, sub-inherited, the factory class returns according to conditions (the method is static and also called static factory). Poor scalability (for example, when adding a new inheritance or implementing a new instance, the method of the factory class needs to be modified), and different products require different additional parameters.

   2. Factory Method mode (Factory Method) The factory method mode removes the static properties of the factory in the simple factory mode, making it inheritable by subclasses. In this way, the pressure on the factory method in the simple factory pattern can be shared by different factory subclasses in the factory method pattern.

   3. The abstract factory pattern (Abstract Factory) provides an interface for creating a group of interdependent objects without specifying their specific classes.

Agency model

1) Static proxy

         When using a static proxy, you need to define an interface or a parent class. The proxy object and the proxy object implement the same interface or inherit the same parent class.

Simulate the save action, define an interface for the save action: IUserDao.java, and then the target object implements the method UserDao.java of this interface. At this time, if you use the static proxy method, you need to implement the IUserDao interface in the proxy object (UserDaoProxy.java). When calling, call the target object by calling the method of the proxy object. It
         should be noted that the proxy object and the target object need to implement the same interface, and then call the method of the target object by calling the same method. This can be done without modifying the target Under the premise of the function of the object, the target function is extended.
   Disadvantages: Because the proxy object needs to implement the same interface as the target object, there will be many proxy classes and too many classes. At the same time, once the interface adds methods, both the target object and the proxy object maintain.

/**
 * 接口
 */
public interface IUserDao {
    
    

    void save();
}

/**
 * 接口实现
 * 目标对象
 */
public class UserDao implements IUserDao {
    
    
    public void save() {
    
    
        System.out.println("----已经保存数据!----");
    }
}

/**
 * 代理对象,静态代理
 */
public class UserDaoProxy implements IUserDao{
    
    
    //接收保存目标对象
    private IUserDao target;
    public UserDaoProxy(IUserDao target){
    
    
        this.target=target;
    }

    public void save() {
    
    
        System.out.println("开始事务...");
        target.save();//执行目标对象的方法
        System.out.println("提交事务...");
    }
}

/**
 * 测试类
 */
public class App {
    
    
    public static void main(String[] args) {
    
    
        //目标对象
        UserDao target = new UserDao();

        //代理对象,把目标对象传给代理对象,建立代理关系
        UserDaoProxy proxy = new UserDaoProxy(target);

        proxy.save();//执行的是代理的方法
    }
}

2) Dynamic proxy

Features:

           The proxy object does not need to implement the interface.The
generation of the proxy object uses the JDK API to dynamically build the proxy object in memory (we need to specify the type of interface implemented by the proxy object/target object)
       .Dynamic proxy is also called: JDK proxy, The interface proxy
JDK implementation proxy only needs to use the newProxyInstance method, but the method needs to receive three parameters. The complete writing is:

static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,InvocationHandler h )

       Note that this method is a static method in the Proxy class, and the three parameters received are in order:
ClassLoader loader: Specify the current target object to use the class loader, and the method to get the loader is fixed
Class<?>[] interfaces, : The type of the interface implemented by the target object, use the generic method to confirm the type
InvocationHandler h: Event processing, when the method of the target object is executed, the method of the event handler will be triggered, and the method of the current execution target object will be passed in as a parameter

to sum up

   The factory pattern mainly assumes the role of creating objects in the production environment, but also hides the creation details for developers. Its purpose is to let the subclass decide which factory class to instantiate through the interface of the created object, so that the object generation process is delayed until In sub-categories. The abstract factory model is to give the generation of factory objects to the abstract factory.

Demonstration example of code

1. Create an object

public class Student {
    
    
	private  Integer id;
    private  String username;
    private  String sex;
    private  String address;
 public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getUsename() {
    
    
        return username;
    }

    public void setUsename(String usename) {
    
    
        this.username = usename;
    }

    public String getSex() {
    
    
        return sex;
    }

    public void setSex(String sex) {
    
    
        this.sex = sex;
    }

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", usename='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

2. Create an interface

public interface IStudent {
    
    
		List<Student> findAll();
}

3. Create a test class

public class Test {
    
    
    /**
     * 入门案例
     * @param args
     */
    public static void main(String[] args)throws Exception {
    
    
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
    
    
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
    }
}

Configuration file refer to this article

Guess you like

Origin blog.csdn.net/weixin_43850343/article/details/112635624