I don’t know why, of all the design patterns, there is a special preference for the proxy pattern. I like this kind of thinking, and the realization of abstracting the common preposition and postposition of many similar methods is really great. After the development of Golang for half a year, I finally developed the Golang-style agent mode in the earlier period of time — in fact, it is no longer the agent mode, and it is more appropriately called one of golang’s small skills

No contrast, no gap, use GO and Java to implement a demo to insert new users

Java style

Let’s take a look at the implementation in Java

UserService interface: public interface UserService {void save(User User); } UserServiceProxy: public class UserServiceProxy implements UserService{private UserService UserService; public UserServiceProxy(UserService userService) { super(); this.userService = userService; } @Override public void save(User user) { System.out.println("-------- open transaction --------");
		userService.save(user);
		System.out.println("-------- close transaction --------"); UserServiceImpl Business class:  public class UserServiceImpl implements UserService { @Override public void save(User user) { System.out.println("Save user"+user); Public class User {private String name; public User(String name) { this.name = name; } @Override public StringtoString() {
		StringBuilder builder = new StringBuilder();
		builder.append("User [name=").append(name).append("]");
		returnbuilder.toString(); }} Test class:  public class Main { public static void main(String[] args) { UserServiceProxy proxy = new UserServiceProxy(new UserServiceImpl()); proxy.save(new User("sivan")); }}Copy the code

Results:

portal

Golang style

Golang, because of the nature of a function parameter, is destined to implement less complex operations such as the proxy pattern, which abstracts pre – and post-actions

package main

import (
	"fmt"
)

func main() {
	saveUser(&user{"sivan"})}type user struct {
	Name string
}

func (u *user) String() string {
	return u.Name
}

func saveUser(user *user) {
	withTx(func() {
		fmt.Printf("Save user %s\n", user.Name)
	})
}

func withTx(fn func()) {
	fmt.Println("Open transaction")
	fn()
	fmt.Println("Closing of business")}Copy the code

Yes, you read that right, go is going to do that, just a few lines of code, and look at the test results

Postscript: each language has the characteristics of each language, a language of an algorithm implementation, into another language, it is also possible, to change a train of thought implementation, should not only its shape.

Lack of strength, unavoidable mistakes, but also please comment section correction.