سؤال

I'm building a set of objects to represent the data abstraction layer sitting between my angularjs application and the backend API. I'm using coffeescript for this (partly to learn coffeescript, partly because I am enjoying their class implementation as I originally hail from a c++ and java background from Days of Yore).

So I have something like

Class Animal
@_cache: {}

...stuff...

Class Dog extends Animal
@_cache: {}

and so on. The issue (which is clearly a syntactic sugar thing) is that I'd like to have all concrete subclasses of Dog have their own instance of the cache. I can handle it either by how I did it above (just override the property), or by replacing that cache with something like @_cache[@constructor.name] = {}, and writing cache accessor functions instead of just directly interacting with it.

Basically, the pattern I want to express is: "Property #{name} should be a class-level (or static) property on this object, and all extending classes should have their own instance of this property", without manually having to do that on each child type. Is there a reasonable pattern to do this?

هل كانت مفيدة؟

المحلول

I have a suggestion, using the dynamic pointer of an instance to its own class: @constructor

In this example, the cache is initialized at first instance creation, and populated in the constructor itself.

class Animal
  # is is just here to distinguish instances
  id: null

  constructor:(@id) ->
    # @constructor aims at the current class: Animal or the relevant subclass
    # init the cache if it does not exists yet
    @constructor._cache = {} unless @constructor._cache?

    # now populates the cache with the created instance.
    @constructor._cache[@id] = @

class Dog extends Animal
   # no need to override anything. But if you wish to, don't forget to call super().

# creates some instances
bart = new Animal 1
lucy = new Dog 1
rob = new Dog 2

console.log "animals:", Animal._cache 
# prints: Object {1=Animal}
console.log "dogs:", Dog._cache
# prints: Object {1=Dog, 2=Dog}

see this fiddle (results on console)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top