西维蜀黍

【Golang】设计模式 - Structural - Adapter

Adaptor Pattern

We have a client code that expects some features of an object (Lightning port), but we have another object called adaptee (Windows laptop) which offers the same functionality but through a different interface (USB port)

This is where the Adapter pattern comes into the picture. We create a struct type known as adapter that will:

  • Adhere to the same interface which the client expects (Lightning port).
  • Translate the request from the client to the adaptee in the form that the adaptee expects. The adapter accepts a Lightning connector and then translates its signals into a USB format and passes them to the USB port in windows laptop.

Refer to https://swsmile.info/post/design-pattern-adapter-pattern/ for Adapter pattern.

  ...


【Golang】设计模式 - Creational - Object Pool

Object Pool Pattern

The object pool creational design pattern is used to prepare and keep multiple instances according to the demand expectation.

As and when needed, a client can request an object from the pool, use it, and return it to the pool. The object in the pool is never destroyed.

Refer to https://swsmile.info/post/design-pattern-flyweight-pattern/#%E4%BA%AB%E5%85%83%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%B9%BF%E6%B3%9B%E4%BD%BF%E7%94%A8 for Flyweight pattern.

  ...


【Golang】设计模式 - Creational - Prototype

Prototype Pattern

Prototype is a creational design pattern that allows cloning objects, even complex ones, without coupling to their specific classes.

All prototype classes should have a common interface that makes it possible to copy objects even if their concrete classes are unknown. Prototype objects can produce full copies since objects of the same class can access each other’s private fields.

  ...


【Golang】设计模式 - Creational - Abstract Factory

Analysis

Abstract Factory Design Pattern is a creational design pattern that lets you create a family of related objects. It is an abstraction over the factory pattern.

Refer to https://swsmile.info/post/design-pattern-factory-pattern/ for Factory pattern.

  ...


【Golang】设计模式 - Creational - Builder

Analysis

The Builder pattern is used when the desired product is complex and requires multiple steps to complete. In this case, several construction methods would be simpler than a single monstrous constructor. The potential problem with the multistage building process is that a partially built and unstable product may be exposed to the client. The Builder pattern keeps the product private until it’s fully built.

In the below code, we see different types of houses (igloo and normalHouse) being constructed by iglooBuilder and normalBuilder. Each house type has the same construction steps. The optional director struct helps to organize the building process.

  ...