2010-09-02 55 views
1

在我们的数据层中,我们需要创建可以从其他“样式”对象继承其值的“样式”对象。在C中实现可继承的样式对象#

示例方案1:

class Style 
{ 
    string Name; 
    string ParentName; 
    // Other properties go here. 
} 

所以,当有这样的样式列表,与父母名称的风格应该继承它的样式值从它的父

方案2:

class ConatiningType 
{ 
    Style BaseStyle; 
    Style MouseHoverStyle; 
} 

在上述情况下,MouseHoverStyle应该继承它离BaseStyle值。

我确定这里有一些推荐的设计模式。如果是这样,请指出这些。

+0

您是否熟悉依赖属性? – Gabe 2010-09-02 20:17:29

+0

您是否尝试复制WPF中的样式继承?我认为这是用于WinForms? – 2010-09-02 20:21:46

回答

1

也许Style本身应该有一个ParentStyle

class Style 
{ 
    private readonly Style parentStyle; 

    private string name; 

    public string Name 
    { 
     get { return name ?? (parentStyle == null ? null : parentStyle.Name); } 
     set { name = value; } 
    } 

    public Style(Style parentStyle) 
    { 
     this.parentStyle = parentStyle; 
    } 
} 

不必使用空支票parentStyle有些烦人,无可否认:(你可以建立一个“默认”的版本是这样的,当然:

class Style 
{ 
    private static readonly Style DefaultStyle = new Style(null) { 
     Name = "", 
     ... 
    }; 

    private readonly Style parentStyle; 

    private string name; 

    public string Name 
    { 
     get { return name ?? parentStyle.Name); } 
     set { name = value; } 
    } 

    public Style(Style parentStyle) 
    { 
     this.parentStyle = parentStyle ?? DefaultStyle; 
    } 
} 

注意,DefaultStyle仍然有一个空parentStyle(如DefaultStyle会期间为null的建设),但如果你给它实际的默认值(“”,0等),那么它永远不会试图推迟到自己不存在的父项。

+0

谢谢,这是一个非常有效的答案。 但是,我正在寻找一个更具可扩展性和性能的更复杂的“模式”,考虑到“价值继承”(我正在寻找的词是什么?上面概述的两种情况。 谢谢 – rqtechie 2010-09-02 20:53:04

+1

@rqtechie:你在哪里看到性能问题?很难建议适用于您未描述的场景的方法... – 2010-09-02 21:00:20