Decorator pattern wasting memory

こ雲淡風輕ζ 提交于 2019-12-13 17:56:43

问题


I have this base class having the following interface:

abstract class Base
{
  abstract public object Val
  {
    get;
  }
}

For any derived classes, Val's value must be specified at object creation time.
The question is: How can I make a derived class do this (hopefully at compile time)?
I tried adding a constructor:

abstract class Base
{
  public Base(object value)
  {
    val = value;
  }

  private object val;

  ...
}

But as you can see then I had to declare a private field to store value in it (because Value is read-only).
The problem arises because I want to add some kind of effect to derived classes using the Decorator/Wrapper pattern introduced in GoF Design Patterns. But because I have declared the field inside Base class, the decorators keep saving a copy of the same data and I end up wasting memory.


回答1:


Try this instead:

abstract class Base 
{
    public Base(object val)
    {
        this.Val = val;
    }

    public object Val { get; private set; }
}

That way, your derived class doesn't need its own field:

public class Derived : Base
{
    public Derived(object val) : base(val) { }
}



回答2:


If it is a decorator, then don't have a field:

public override object Val {
    // add any decoration effects here if needed
    get { return tail.Val; }
}

Where tail is the thing you are decorating.


However, it sounds like you mean inheritance (not decoration) - if so:

abstract class BaseClass {
    protected BaseClass(object val) {...}
}
class ConcreteType : BaseClass {
    public ConcreteType(object val)
        : base(val) { }
}

Here the base class could even handle the storage etc.



来源:https://stackoverflow.com/questions/8466706/decorator-pattern-wasting-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!