diff --git a/creational/factory_method.go b/creational/factory_method.go new file mode 100644 index 0000000..16dee30 --- /dev/null +++ b/creational/factory_method.go @@ -0,0 +1,33 @@ +package data + +import "io" + +type Store interface { + Open(string) (io.ReadWriteCloser, error) +} + + +type StorageType int + +const ( + DiskStorage StorageType = 1 << iota + TempStorage + MemoryStorage +) + +func NewStore(t StorageType) Store { + switch t { + case MemoryStorage: + return newMemoryStorage( /*...*/ ) + case DiskStorage: + return newDiskStorage( /*...*/ ) + default: + return newTempStorage( /*...*/ ) + } +} + +s, _ := NewStore(data.MemoryStorage) +f, _ := s.Open("file") + +n, _ := f.Write([]byte("data")) +defer f.Close() diff --git a/creational/object_pool.go b/creational/object_pool.go new file mode 100644 index 0000000..6ef65a5 --- /dev/null +++ b/creational/object_pool.go @@ -0,0 +1,27 @@ +package pool + +type Pool chan *Object + +func New(total int) *Pool { + p := make(Pool, total) + + for i := 0; i < total; i++ { + p <- new(Object) + } + + return &p +} + + + +p := New(2) + +select { +case obj := <-p: + obj.Do( /*...*/ ) + + p <- obj +default: + // No more objects left — retry later or fail + return +} diff --git a/profiling/profile.go b/profiling/profile.go new file mode 100644 index 0000000..e123f45 --- /dev/null +++ b/profiling/profile.go @@ -0,0 +1,25 @@ +package profile + +import ( + "time" + "log" +) + +func Duration(invocation time.Time, name string) { + elapsed := time.Since(invocation) + + log.Printf("%s lasted %s", name, elapsed) +} + +func BigIntFactorial(x big.Int) *big.Int { + // Arguments to a defer statement is immediately evaluated and stored. + // The deferred function receives the pre-evaluated values when its invoked. + defer Duration(time.Now(), "IntFactorial") + + y := big.NewInt(1) + for one := big.NewInt(1); x.Sign() > 0; x.Sub(x, one) { + y.Mul(y, x) + } + + return x.Set(y) +} diff --git a/structural/decorate.go b/structural/decorate.go new file mode 100644 index 0000000..4dccbe6 --- /dev/null +++ b/structural/decorate.go @@ -0,0 +1,28 @@ +package main + +type Object func(int) int + +func LogDecorate(fn Object) Object { + return func(n int) int { + log.Println("Starting the execution with the integer", n) + + result := fn(n) + + log.Println("Execution is completed with the result", result) + + return result + } +} + +func Double(n int) int { + return n * 2 +} + +func main(){ + f := LogDecorate(Double) + f(5) +} + + +// Starting execution with the integer 5 +// Execution is completed with the result 10