装饰器模式浪费内存 [英] Decorator pattern wasting memory
问题描述
我有一个具有以下接口的基类:
I have this base class having the following interface:
abstract class Base
{
abstract public object Val
{
get;
}
}
对于任何派生类,必须在对象创建时指定Val
的值 .
问题是:我如何使成为派生类(希望在编译时)做到这一点?
我尝试添加一个构造函数:
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;
...
}
但是正如您所看到的,我不得不声明一个私有字段来在其中存储值(因为Value是只读的).
出现问题是因为我想使用GoF设计模式中引入的Decorator/Wrapper模式向派生类添加某种效果.但是因为我已经在Base类中声明了该字段,所以装饰器不断保存相同数据的副本,最终浪费了内存.
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.
推荐答案
尝试以下方法:
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) { }
}
这篇关于装饰器模式浪费内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!