How to resolve the algorithm Singleton step by step in the TXR programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Singleton step by step in the TXR programming language

Table of Contents

Problem Statement

A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Singleton step by step in the TXR programming language

Source code in the txr programming language

;; Custom (:singleton) clause which adds behavior to a class
;; asserting against multiple instantiation.
(define-struct-clause :singleton ()
  ^((:static inst-count 0)
    (:postinit (me)
      (assert (<= (inc me.inst-count) 1)))))

(defstruct singleton-one ()
  (:singleton)
  (:method speak (me)
    (put-line "I am singleton-one")))

(defstruct singleton-two ()
  (:singleton)
  (:method speak (me)
    (put-line "I am singleton-two")))

;; Test

;; Global singleton
(defvarl s1 (new singleton-one))

;; Local singleton in function (like static in C)
;; load-time evaluates once.
(defun fn ()
  (let ((s2 (load-time (new singleton-two))))
    s2.(speak)))

s1.(speak)
(fn) ;; multiple calls to fn don't re-instantiate singleton-two
(fn)
(put-line "so far, so good")
(new singleton-two) ;; assertion gooes off

  

You may also check:How to resolve the algorithm Towers of Hanoi step by step in the Gambas programming language
You may also check:How to resolve the algorithm Increment a numerical string step by step in the Maxima programming language
You may also check:How to resolve the algorithm Simple turtle graphics step by step in the Logo programming language
You may also check:How to resolve the algorithm Set puzzle step by step in the Julia programming language
You may also check:How to resolve the algorithm Identity matrix step by step in the Frink programming language