这是面试中被问到的问题。
There is a
Label
with a propertyText
In one page a label is simpleLabel
, in other pages it may handle any one or combination of the below actions
Clickable
Resizable
DraggableHow 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
但是,我觉得这是不正确的方法,因为我不想添加那些具体的类。我想避免使用 ClickableAndDraggableLabel
或 ClickableDraggableResizableLabel
。
有没有什么设计模式可以在不添加这些具体类的情况下解决这个问题?
最佳答案
我会使用 Decorator pattern .它在 .net 世界中广泛用于不同类型的流,例如,它允许您为字节流编写加密的、压缩的、文本流包装器。类图取自wiki
你的例子在实现中并不是那么简单,但使用不需要其他类来实现新的组合行为:
// 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/