Advanced Points on Classes

Damien Cassou, Stéphane Ducasse and Luc Fabresse http://stephane.ducasse.free.fr

Roadmap

Roadmap

Sharing State?

How do you share state between instances of a class?

Object subclass: #Color
   instanceVariableNames: 'rgb cachedDepth...'
   classVariableNames: 'ColorRegistry ComponentMask...'
   package: 'Graphics-Primitives'

Class Variables

Class Variable Access

Class Variable Access

Roadmap

Class Instance Variables

A class can have instance variables like any object

RPackageSet class
   instanceVariableNames: 'cachePackages'

No Sharing with Class Instance Variables

Each instance has a different value for cachePackages

Singleton Design Pattern

Singleton with a Class Instance Variable

WebServer class
   instanceVariableNames: 'uniqueInstance'

WebServer class >> new
   self error: 'Can''t create a new instance'

WebServer class >> uniqueInstance
   ^ uniqueInstance
      ifNil: [ uniqueInstance := super new ]

Consequence:

Singleton with a Class Variable

Object subclass: #WebServer
   instanceVariableNames: ''
   classVariableNames: 'UniqueInstance'
   package: 'Web'

WebServer class >> new
   self error: 'Can''t create a new instance'

WebServer class >> uniqueInstance
   ^ UniqueInstance
      ifNil: [ UniqueInstance := super new ]

Consequence:

Roadmap

Class Initialization

How and when are classes initialized?

Class Initialization

A class is initialized

Color initialize

Color Initialization

Color class >> initialize
   "Externally, the red, green, and blue components of color are floats in the range [0.0..1.0]. Internally, they are represented as integers in the range [0..ComponentMask] packing into a small integer to save space and to allow fast hashing and equality testing."
   ComponentMask := 1023.
   HalfComponentMask := 512. "used to round up in integer calculations"
   ComponentMax := 1023.0. "used to normalize components"
   RedShift := 20.
   GreenShift := 10.
   BlueShift := 0.
   self initializeIndexedColors.
   self initializeColorRegistry.
   self initializeGrayToIndexMap.

Warning

What You Should Know

/