Template Method in Golang

Source: Internet
Author: User
Tags key string mysql connect
This is a creation in Article, where the information may have evolved or changed.

Preface

As container cloud technology matures, microservices architectures are becoming more and more hot. Under the microservices architecture, we decompose the original single application into a series of independent, focused microservices based on functional boundaries. Each microservices corresponds to a component in a traditional application, but can be compiled, deployed, and scaled independently. Each team can freely choose the most appropriate technology stack, such as programming language and database, according to the needs of its services and the status of industry development. Golang language in the prime of the years, not only kubernetes, Openshif and Docker and other container cloud-related open source project development language is Golang, and many of the real-time requirements of the micro-service team also choose Golang as the main development language.

In this background, the author also began a journey of Golang. Golang as a new static type development language, compared with the existing development language concise, interesting but super powerful, with a lot of exciting new features, the most exciting of the author's two features are:

    1. Goroutine and Channel
    2. Interface

If Goroutine and channel are the cornerstone of Golang's concurrency model, making Golang a very beautiful landscape in today's era of clustering and multicore, interface is the cornerstone of the Golang of the entire type system, Let Golang in the exploration of basic programming philosophy to reach an unprecedented height.

One of the design philosophies of Golang is that "less is more", there is no universal language, and the way to keep it simple is to provide only one way to do things and to do things to the fullest. Guided by this principle, Golang's support for object-oriented programming is simple and elegant:

    1. The simplicity is that Golang does not follow many of the concepts in traditional object-oriented programming, such as inheritance, virtual functions, constructors and destructors, hidden this pointers, etc.
    2. Elegance is that Golang support for object-oriented programming is a natural component of the language type system, and the entire type system is interface in series and seamless. Most languages offer interface, but their interface are different from the interface in Golang's Interface,golang and the biggest difference from other languages is its non-invasive nature.

The user story to be developed by the author involves a series of algorithm steps, that is, the algorithm framework for multiple network plane operations is the same, and the behavior of the specific steps is somewhat different, so I think of a design pattern-template method. Unlike other object-oriented languages, Golang is naturally a modular design.

This paper tries to realize the template method with Golang, and experience the charm of modular design together with the readers.

Template Method Review

Defined

Template method pattern is the framework for defining an algorithm in an operation, and some steps are deferred to subclasses so that subclasses can redefine some specific steps of the algorithm without changing the framework of an algorithm.

The general class diagram for the template method is as follows:


Template-method.png

Although the general class diagram of the template method is very simple, it is a very extensive design pattern.

Abstract templates

AbstractClass is called an abstract template, and its methods are divided into two categories:

    1. Basic method: Also called basic operation, is a method implemented by a subclass and is called in a template method
    2. Template method: Can have one or several, is generally an algorithm framework, the implementation of the basic method of scheduling, complete the fixed logic.

The following is an example of C + + code:

//AbstractClass.hstruct AbstractClass{    virtual ~AbstractClass() = default;    void templateMethod();private:    virtual void doAnyThing() = 0;    virtual void doSomeThing() = 0;};//AbstractClass.cppvoid AbstractClass::templateMethod(){    doAnyThing();    doSomeThing();}

Specific templates

ConcreteClass1 and ConcreteClass2 belong to specific templates that implement one or more of the abstract methods defined by the parent class, that is, the basic method of the parent class definition is implemented in the subclass.

The following is an example of C + + code:

//ConcreteClass1.hstruct ConcreteClass1 : AbstractClass{private:    virtual void doAnyThing() override;    virtual void doSomeThing() override;};//ConcreteClass1.cppvoid ConcreteClass1::doAnyThing(){    ...}void ConcreteClass1::doSomeThing(){    ...}

Note : ConcreteClass2 and ConcreteClass2 are similar in code, we will not repeat them.

Instantiate a template method

Introduce problems

Assuming we have two databases, MySQL and Oracle, the user operates with the same algorithm framework, and the specific behavior of the algorithm steps is different, such as the connection interface of the database and the implementation of the shutdown interface.
We assume that the user's input is ternary (table, key, value) and expects the database to have a transactional operation, the framework of the core algorithm is:

  1. Connecting to a database
  2. Querying for the existence of a record for a ternary group entered by the user
  3. Insert a new record if it does not exist
  4. Update the record if it exists
  5. Close the database

Note : We also assume that the database has a data logging activity detection function, when a data record has not been referenced for a long time, it is deleted from the database, so users do not care about the deletion of records.

Note : The problem is the author's own fiction.

Modeling

After modeling according to the interface characteristics of Golang, the class diagram of the template method is as follows:


Template-method-golang.png

The following is a description of the diagram:

    1. Golang's interface contains only pure method declarations, then the template method cannot be defined in interface, so a class (struct) must be added, which we remember as Dbtrans. Dbtrans holds the interface db through the member variable, which dynamically binds the specific DB instance at run time, and we use a one-way association to represent the relationship. The Dbtrans exec () method in the figure is used to implement the algorithm framework, and the abstract template in the corresponding pattern
    2. In Golang, when a class implements all the functions required by an interface, we say that the class implements the interface, otherwise the class is not related to the interface. There is no forced contractual relationship (inheritance) between classes and interfaces, and inheritance and polymorphism are implemented by combining and dynamically binding, and we use dashed lines to represent this invisible inheritance relationship. In the diagram, MySQL and Oracle implement the interface DB respectively, the specific template in the corresponding mode

Realize

Db

DB is the core feature interface, and the implementation code is:

type Db interface {    Connect()    Close()    InsertRecord(tableName, key, value string)    GetRecord(tableName, key string) (err error, value string)    UpdateRecord(tableName, key, value string)}

Dbtrans

Dbtrans is the struct that hosts the template method, and the implementation code is:

type DbTrans struct {    Inst Db}func (this *DbTrans) Exec(tableName, key, value string) {    if this.Inst == nil {        return    }    this.Inst.Connect()    if err, _ := this.Inst.GetRecord(tableName, key); err != nil {        this.Inst.InsertRecord(tableName, key, value);    } else {        this.Inst.UpdateRecord(tableName, key, value)    }    this.Inst.Close()}

description : The algorithm framework is exactly the same as the framework given in the "Introducing Problems" section

Mysql

MySQL is a struct that hosts specific template methods, and the code is implemented as follows:

type Mysql struct {}func (_ *Mysql) Connect() {    fmt.Println("mysql connect...")}func (_ *Mysql) Close() {    fmt.Println("mysql close...\n")}func (_ *Mysql) InsertRecord(tableName, key, value string) {    fmt.Printf("mysql tablename-%v insert record(%v, %v) succ!\n", tableName, key, value)}func (_ *Mysql) GetRecord(tableName, key string) (err error, value string) {    i := rand.Intn(5)    if i < 2 {        fmt.Println("mysql", tableName, "table get record by", key, "failed!")        return errors.New("record is not existed"), "nop"    }    fmt.Println("mysql", tableName, "table get record by", key, "succ!")    return nil, "nop"}func (_ *Mysql) UpdateRecord(tableName, key, value string) {    fmt.Printf("mysql tablename-%v update record(%v, %v) succ!\n", tableName, key, value)}

Let's look at the Getrecord method implemented in MySQL:

    1. If the random number between [0, 5] is less than the other, the simulation fails to find
    2. If the lookup fails, insert the record
    3. If the lookup succeeds, the record is updated

Oracle

Oracle is similar to MySQL and does not repeat it.

Client

The client is implemented in the main function, and the code is implemented as follows:

func main() {    trans := new(DbTrans)    trans.Inst = new(Mysql)    trans.Exec("department", "cloudman", "a architect and be good at openstack")    trans.Inst = new(Oracle)    trans.Exec("department", "cloudman", "a architect and be good at openstack and like dancing")}

Obviously, the user triggered the transaction operation of two databases, one is MySQL, the other is Oracle, and the algorithm framework of the two transactions is Dbtrans.

Log

To run the Golang code for the template method, log the following:

mysql connect...mysql department table get record by cloudman failed!mysql tablename-department insert record(cloudman, a architect and be good at openstack) succ!mysql close...oracle connect...oracle department table get record by cloudman succ!oracle tablename-department update record(cloudman, a architect and be good at openstack and like dancing) succ!oracle close...

Summary

This paper first reviews the common definition and implementation of template methods, then introduces a problem, through the modeling and implementation steps to instantiate the Golang version of the template method, which will be developed by the author of the user story has some value, but also hope that the reader deeply understand the Golang interface have certain help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.