mardi 27 septembre 2022

What's an appropriate design pattern to call outer struct's method in Golang?

For example, I have a parent struct Connection and a child struct Dialect as follows:

type Connection struct {
    conn *net.TCPConn
    databaseDialect DatabaseDialect
}

func (c *Connection) modifySQL(sql string) (string, error) {
}

// Close cleans up
func (c *Connection) Close() error {
    ...
}

func (c *Connection) handleConnection() error {
    c.databaseDialect = &PostgreSQLDialect{
        conn: c.conn,
        modifySQLFunc: c.modifySQL,
    }
    return dialect.HandleConnection()
}

type DatabaseDialect interface {
    HandleConnection()
}

type PostgreSQLDialect struct {
    conn *net.TCPConn
    modifySQLFunc func(string) (string, error)
}

func (d *PostgreSQLDialect) HandleConnection() error {
    buff := make([]byte, 0xffff)
    d.conn.Read(buff)
    sql := parseToSQL(buff) // parse buffer to SQL statements
    
    // call outer's function here
    sql, err = d.modifySQLFunc(sql)
    ...
}

You can see that the outer function modifySQL is passed in PostgreSQLDialect. but things can be more complicated. Say if we got more outer functions needed to be called. For instance, when a connection is closed. We need to call the outer function Close() to clean up resources. So I'm curious if PostgreSQLDialect needs to have a reference variable to the outer struct Connection. But I just feel like it's not a good design to make my code well-architectured.

Is there any design pattern good for this case? Any open source repo, source code or article is welcome.

Aucun commentaire:

Enregistrer un commentaire