Trace  Hoeger

Trace Hoeger


The Decorator Pattern In Go

The final product is oddly satisfying.

 Image for post


he Decorator pattern is an incredibly useful and flexible technique to create forward-thinking code. It allows you to add functionality to an object dynamically at run time instead of compile time. What this means is that you don’t have to manually write new code to extend an object’s feature set, you can simply use the decorator pattern to add behavior as you need it!

It also solves the issue of becoming restricted by an extensive sub-class architecture. Instead of getting lost in inheritance, the Decorator pattern uses lots of smaller classes (in Go’s case structs) in order to wrap functionality around other objects. This way we can have many objects with variations of functionality instead of having to define each individual class.

We will split this article into three parts including the use cases, UML diagram, and implementation in Go for the Decorator pattern.

Use Cases

The Decorator pattern can be applied to a wide range of situations and scenarios. These include:

  • A Shopping Cart — each item could be wrapped around a central customer order object in order to keep track of the total order price.
  • Data Streaming — as you transfer data you may find out you want various combinations of encryption, compression, or formatting behavior depending on what the client wants.
  • Legacy Code — if you have an object that you can’t change but need to extend its feature capability, you could do so with Decorator pattern.

UML Diagram

This pattern entails a pretty compact diagram. Starting from the top, the Component interface requires the method operation() to be implemented. This is done by both the ConcreteComponent and the Decorator objects themselves. Note the aggregation relationship between Component and Decorator meaning that a Component may have zero to many Decorators, but a Decorator cannot exist without a Component.

Image for post

Essentially, we have a Component interface with its most basic form implemented by ConcreteComponent. Then the Decorator can be implemented by a ConcreteDecorator and wrapped around the ConcreteComponents.

#programming #tutorial #golang #design

What is GEEK

Buddha Community

The Decorator Pattern In Go
Fannie  Zemlak

Fannie Zemlak


What's new in the go 1.15

Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.

As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.

#go #golang #go 1.15 #go features #go improvement #go package #go new features

Samanta  Moore

Samanta Moore


Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

Head First Design Patterns using Go — 3. Decorating Objects: The Decorator Pattern

A descriptive series on the design patterns based on the O’Reily book of the same name adapted to Go from Java

Table of Contents

0.  Introduction

  1. Welcome to Design Patterns: the Strategy Pattern
  2. Keeping your Objects in the know: the Observer Pattern
  3. Decorating Objects: the Decorator Pattern
  4. Baking with OO goodness: the Factory Pattern
  5. Encapsulating Invocation: the Command Pattern
  6. Being Adaptive: the Adapter and Facade Patterns
  7. Encapsulating Algorithms: the Template Method Pattern
  8. Well-managed Collections: the Iterator and Composite Patterns
  9. The State of Things: the State Pattern
  10. Controlling Object Access: the Proxy Pattern
  11. Patterns of Patterns: Compound Patterns

This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.

Problem Statement 1:

  • Welcome to Starbuzz Coffee.
  • During initial days, they have limited set of offerings — HouseBlend, DarkRoast, Decaf, Espresso.
  • Design a system to get the cost of the beverage ordered.


#golang #design-patterns #programming #go

Elian  Harber

Elian Harber


Go-patterns: Curated List Of Go Design Patterns, Recipes and Idioms

Go Patterns

A curated collection of idiomatic design & application patterns for Go language.

Creational Patterns

Abstract FactoryProvides an interface for creating families of releated objects
BuilderBuilds a complex object using simple objects
Factory MethodDefers instantiation of an object to a specialized function for creating instances
Object PoolInstantiates and maintains a group of objects instances of the same type
SingletonRestricts instantiation of a type to one object

Structural Patterns

BridgeDecouples an interface from its implementation so that the two can vary independently
CompositeEncapsulates and provides access to a number of different objects
DecoratorAdds behavior to an object, statically or dynamically
FacadeUses one type as an API to a number of others
FlyweightReuses existing instances of objects with similar/identical state to minimize resource usage
ProxyProvides a surrogate for an object to control it's actions

Behavioral Patterns

Chain of ResponsibilityAvoids coupling a sender to receiver by giving more than object a chance to handle the request
CommandBundles a command and arguments to call later
MediatorConnects objects and acts as a proxy
MementoGenerate an opaque token that can be used to go back to a previous state
ObserverProvide a callback for notification of events/changes to data
RegistryKeep track of all subclasses of a given class
StateEncapsulates varying behavior for the same object based on its internal state
StrategyEnables an algorithm's behavior to be selected at runtime
TemplateDefines a skeleton class which defers some methods to subclasses
VisitorSeparates an algorithm from an object on which it operates

Synchronization Patterns

Condition VariableProvides a mechanism for threads to temporarily give up access in order to wait for some condition
Lock/MutexEnforces mutual exclusion limit on a resource to gain exclusive access
MonitorCombination of mutex and condition variable patterns
Read-Write LockAllows parallel read access, but only exclusive access on write operations to a resource
SemaphoreAllows controlling access to a common resource

Concurrency Patterns

N-BarrierPrevents a process from proceeding until all N processes reach to the barrier
Bounded ParallelismCompletes large number of independent tasks with resource limits
BroadcastTransfers a message to all recipients simultaneously
CoroutinesSubroutines that allow suspending and resuming execution at certain locations
GeneratorsYields a sequence of values one at a time
ReactorDemultiplexes service requests delivered concurrently to a service handler and dispatches them syncronously to the associated request handlers
ParallelismCompletes large number of independent tasks
Producer ConsumerSeparates tasks from task executions

Messaging Patterns

Fan-InFunnels tasks to a work sink (e.g. server)
Fan-OutDistributes tasks among workers (e.g. producer)
Futures & PromisesActs as a place-holder of a result that is initially unknown for synchronization purposes
Publish/SubscribePasses information to a collection of recipients who subscribed to a topic
Push & PullDistributes messages to multiple workers, arranged in a pipeline

Stability Patterns

BulkheadsEnforces a principle of failure containment (i.e. prevents cascading failures)
Circuit-BreakerStops the flow of the requests when requests are likely to fail
DeadlineAllows clients to stop waiting for a response once the probability of response becomes low (e.g. after waiting 10 seconds for a page refresh)
Fail-FastChecks the availability of required resources at the start of a request and fails if the requirements are not satisfied
HandshakingAsks a component if it can take any more load, if it can't, the request is declined
Steady-StateFor every service that accumulates a resource, some other service must recycle that resource

Profiling Patterns

Timing FunctionsWraps a function and logs the execution


Functional OptionsAllows creating clean APIs with sane defaults and idiomatic overrides


Cascading FailuresA failure in a system of interconnected parts in which the failure of a part causes a domino effect

Download Details:

Author: tmrts
Source Code: 
License: Apache-2.0 license

#go #golang #pattern 

Zena  Sporer

Zena Sporer


Design Patterns — Decorator Design Pattern


The decorator design pattern is a software design pattern that helps you add responsibilities to an object at runtime. This pattern is considered to be a structural design pattern. This type of pattern focuses on the relationships between classes and how they can help solve specific problems.

The Gang of Four, in their book Design Patterns: Elements of Reusable Object-Oriented Software, defined the intent of decorator pattern like this:

Intent:_ Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality._

One of the key characteristics of this design pattern is that it follows the Single Responsibility Principle (SRP). This is because each “decoration” you add to an object, will be encapsulated within a class. This class’s responsibility will be to handle everything related to adding that decoration to that object.

Time to assemble a 🍔

For purposes of learning the decorator pattern, let’s assume you want to create an object of type Hamburger.

How a hamburger is assembled varies. According to Burger King, there are 221,184 possible ways to order a Whopper. It will take you at least 200 years to eat these many hamburgers if you were to eat one hamburger for breakfast, lunch, and dinner! The possibilities are endless.

In a world without the decorator pattern, an approach you might take is to create a parent Hamburger class and then subclasses for the different types of hamburgers. This could easily become a maintenance headache as it will make troubleshooting more difficult due to the complexity of multiple levels of inheritance.

#design-patterns #java #software-engineering #decorator-pattern #programming