c# - 在不创建新类的情况下添加更多行为

标签 c# oop design-patterns design-principles

这是面试中被问到的问题。

There is a Label with a property Text
In one page a label is simple Label, in other pages it may handle any one or combination of the below actions
Clickable
Resizable
Draggable

How do you design this label component that applies OOP design Principle & Design Pattern?

我说过我会创建以下内容:

public class Label
{
  public string Text{get;set;}
}
public interface IClickable
{
 void Click();
}

public interface IDraggable
{
 void Drag();
}
public interface IResizable
{
 void Resize();
}

这样如果客户想要可调整大小的标签

public class ResizableLabel:Label,IResizable
{
  ....
}

同样的方式 ClickableLable, DraggableLabel

但是,我觉得这是不正确的方法,因为我不想添加那些具体的类。我想避免使用 ClickableAndDraggableLabelClickableDraggableResizableLabel

有没有什么设计模式可以在不添加这些具体类的情况下解决这个问题?

最佳答案

我会使用 Decorator pattern .它在 .net 世界中广泛用于不同类型的流,例如,它允许您为字节流编写加密的、压缩的、文本流包装器。类图取自wiki

enter image description here

你的例子在实现中并不是那么简单,但使用不需要其他类来实现新的组合行为:

// Define other methods and classes here
public class Label
{
    public string Text{get;set;}

    public virtual void MouseOver(object sender, EventArgs args) { /*some logic*/ }
    public virtual void Click(object sender, EventArgs args) {  /*some logic*/ }

    //other low level events
}

public class ClikableLabel : Label
{
    private Label _label;

    public ClikableLabel(Label label)
    {
        _label = label; 
    }

    public override void Click(object sender, EventArgs args) 
    {   
        //specific logic
        _label.Click(sender, args);
    }
}

public class DraggableLabel : Label
{
    private Label _label;

    public DraggableLabel(Label label)
    {
        _label = label; 
    }

    public override void Click(object sender, EventArgs args) 
    {   
        //specific logic
        _label.Click(sender, args);
    }
}
public class ResizableLabel : Label
{
    private Label _label;

    public ResizableLabel(Label label)
    {
        _label = label; 
    }

    public override void MouseOver(object sender, EventArgs args) 
    {   
        //specific logic
        _label.MouseOver(sender, args);
    }

    public override  void Click(object sender, EventArgs args) 
    {
        //specific logic
        _label.Click(sender, args);
    }
}

现在你可以

var clickableDragableLabel = new ClikableLabel(new DraggableLabel(new Label{Text = "write me!"}));

var makeItResizable = new ResizableLabel(clickableDragableLabel);

关于c# - 在不创建新类的情况下添加更多行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16099669/

相关文章:

ruby - 试图创建一个从同一类中选择随机方法的方法

PHP 绑定(bind)参数() : Number of variables doesn't match number of parameters in prepared statement

php - 在继承层次结构中重载构造函数是否意味着需要组合?

c# - 如何在我的业务逻辑层中管理统一性?

c# - 如何计算 Nullable<T> 数据类型的大小

c# - Wpf DataGrid 只显示空行

c# - 使用 AddNew() 调用参数化构造函数

c# - 系统找不到进程启动中指定的文件异常(tscon.exe)

java - Fragments 作为静态内部类与独立公共(public)类的设计逻辑是什么?

php - setter/getter 中重复开关的设计模式?