我正在研究我的设计模式,我在编码中尚未认真使用的一种模式是装饰模式.
我理解这种模式,但我想知道的是现实世界中一些具体的例子,装饰者模式是最佳/最佳/优雅的解决方案.需要装饰器模式的特定情况非常方便.
谢谢.
我在维基百科中读到,Decorator模式用于.Net和Java IO类.
任何人都能解释一下这是如何使用的吗?它有一个可能的例子,它有什么好处?
维基百科上有一个Windows窗体的例子,但我想知道Java IO类是如何发生的.
我有点被打字稿装饰者和他们如何解释.据说他们通过将元数据与它相关联来"装饰"一个类.我似乎无法理解元数据如何与类的实例相关联的概念.以角度2为例.
@Component(
{
selector:...
}
)
export class foo { ... }
Run Code Online (Sandbox Code Playgroud)
目前我理解angular将实例化类foo并以某种方式将实例与装饰器的参数相关联,以便它可以提供服务,指令和模板.所有这些似乎也可以通过类继承来实现.如果我有一个Component类并让我的组件扩展该类,为什么不能有角度,然后提供这些参数,当它以与props做反应的方式引导时,并在这个使用场景中完全摆脱装饰器.
class Component { ... } //say this has members such as selector, services, directives, etc..
class Foo extends Component { ... }
Run Code Online (Sandbox Code Playgroud)
然后你将使用它在bootstrap/runtime实例化它
new Foo(ElementName, Directives, Services, etc..)
Run Code Online (Sandbox Code Playgroud)
通过反应,这在技术上是在引擎盖下进行的.您派生了组件并实现了它的方法.如果在实例化时需要传递信息,则传入props对象.
请赐教.
我对模式很新,我正在研究装饰模式,我必须编写一个程序.
在线学习,我找到了一个Decorator模式的例子(它是Java伪代码):
class Solution1
{
static interface Component
{
void doStuff();
}
static class MyComponent implements Component
{
public void doStuff()
{
// ...
}
}
static class ComponentDecorator implements Component // This is the Decorator pattern.
{
private final Component component;
public ComponentDecorator(Component component)
{
this.component = component;
}
public void doStuff()
{
this.component.doStuff();
}
}
static class ComponentDecorator1 extends ComponentDecorator
{
public ComponentDecorator1(Component component)
{
super(component);
}
private void doExtraStuff1()
{
// ...
}
public void doStuff()
{ …
Run Code Online (Sandbox Code Playgroud)