0

我需要向对象添加额外的数据——但我不需要添加功能。因此,以下是经典 GOF 装饰器模式的示例吗?

class ClassIWantToDecorate
{
    public string GetData() { return "data"; }
}

class Decorator
{
    private ClassIWantToDecorate _classIWantToDecInstance = null;
    private string _additionalData;
    public Decorator(ClassIWantToDecorate classIWantToDec, string additionalData)
    {
        _classIWantToDecInstance = classIWantToDec;
        _additionalData = additionalData;
    }

    public string DataINeed()
    {
        return _classIWantToDecInstance.GetData();
    }

    public string AdditionalDataINeed()
    {
        return _additionalData;
    }
}
4

2 回答 2

2

不,我会说这只是composition

装饰器将是这样的:

interface DataINeedProvider {
    string DataINeed();
}

class LoggingDecorator implements DataINeedProvider
{
    private DataINeedProvider _classIWantToDecInstance = null;
    private Logger logger = new Logger();
    public LoggingDecorator(DataINeedProvider classIWantToDec) {
        _classIWantToDecInstance = classIWantToDec;
    }

    public string DataINeed()
    {
        logger.log("DataINeed has been called");
        return _classIWantToDecInstance.DataINeed();
    }
}

PS:抱歉,如果这不是有效的 C# 语法。我是一名 Java 开发人员。

于 2012-12-24T23:22:28.070 回答
1

你的实现的问题是你的装饰器接口与被装饰对象的接口不兼容。

一个有效的装饰器解决方案是:

interface ClassIWantToDecorateInterface {
  public string GetData();
}

class ClassIWantToDecorate implements ClassIWantToDecorateInterface {
    public string GetData() { return "data"; }
}

class Decorator implements ClassIWantToDecorateInterface {
    private ClassIWantToDecorateInterface _classIWantToDecInstance = null;
    private string _additionalData;
    public Decorator(ClassIWantToDecorateInterface classIWantToDec, string additionalData)
    {
        _classIWantToDecInstance = classIWantToDec;
        _additionalData = additionalData;
    }

    public string GetData() {
        return _classIWantToDecInstance.GetData();
    }

    public string AdditionalDataINeed() {
        return _additionalData;
    }
}

(我使用 java 语法是因为我不确定您使用的是 C# 还是 Java。根据语法它可能是两者)

于 2012-12-24T23:23:14.373 回答