Class [java | coffee]脚本中继承类静态重写的模式?

Class [java | coffee]脚本中继承类静态重写的模式?,class,oop,design-patterns,inheritance,coffeescript,Class,Oop,Design Patterns,Inheritance,Coffeescript,我正在构建一组对象来表示位于angularjs应用程序和后端API之间的数据抽象层。我用咖啡稿来学习(部分是为了学习咖啡稿,部分原因是我喜欢他们的课堂实现,因为我最初是从C++和java背景下从昔日开始的)。 所以我有点像 Class Animal @_cache: {} …东西 Class Dog extends Animal @_cache: {} 等等。问题是(这显然是一个语法上的甜点),我想让Dog的所有具体子类都有自己的缓存实例。我可以通过上面的方法来处理它(只需重写属性),或者用

我正在构建一组对象来表示位于angularjs应用程序和后端API之间的数据抽象层。我用咖啡稿来学习(部分是为了学习咖啡稿,部分原因是我喜欢他们的课堂实现,因为我最初是从C++和java背景下从昔日开始的)。

所以我有点像

Class Animal
@_cache: {}
…东西

Class Dog extends Animal
@_cache: {}
等等。问题是(这显然是一个语法上的甜点),我想让Dog的所有具体子类都有自己的缓存实例。我可以通过上面的方法来处理它(只需重写属性),或者用@u cache[@constructor.name]={}之类的东西替换该缓存,并编写缓存访问器函数,而不是直接与它交互


基本上,我想要表达的模式是:“Property#{name}应该是这个对象上的类级(或静态)属性,所有扩展类都应该有自己的这个属性实例”,而不必在每个子类型上手动执行。有没有一个合理的模式来做到这一点

我有一个建议,使用实例的动态指针指向它自己的类:
@constructor

在本例中,缓存在第一次创建实例时初始化,并在构造函数中填充

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}

请参见此(控制台上的结果)

为什么他们需要自己的缓存?这些实例是专门缓存的吗?那么,显式声明自己的缓存是值得的。无论如何,我认为您正在寻找AbstractFactory模式,或者一个简单的“动物类”混入。如果您将其设置为静态,那么它将不会被继承,它将属于一个特定的类。那么为什么不简单地做一个
Animal.cache={}
?从那时起,您将必须访问
Animal
类中的缓存,而不是直接通过任何实例。如果是这种情况,您也可以单独定义一个缓存对象。