上海
类型:工装设计师
答:装饰者模式可以动态地给一个对象增加其他职责。就扩展对象功能来说,装饰者模式比生成子类更为灵活。(定义)不给你写代码了,写了估计你也不看。
简单的给你解释吧:你只会做一件事情A,我想让你去做B-A这件事情,不改变你的行为,你肯定不会做的。但是小明会做另一件事情B,所以我就可以让小明去做B,并且告诉小明做完后 如果遇见你 就让你做事情A。让后我们你们两个放在一块,让小明做B,然后事情B-A就可以被做了。同样我想完成事情C-A,只要找到会做C的小王就可以了。
在这里你就是被装饰者,小明和小王就是装饰者。之所以把你叫做装饰者,可能是因为你做的事情是主要的事情。其实这些都是可以灵活利用的 。
建议你看书header first 设计模式
如果想看代码,百度太多了。
如果不明白,可以追问。
• 2019/10/07 11:21
福州
类型:工装设计师
答:
DataInputStreambis=newDataInputStream(newBufferedInputStream(newFileInputStream("File")));BufferedInputStreambis2=newBufferedInputStream(newDataInputStream(newFileInputStream("File")));
packagedecorator;
publicclassSonimplementsWork{
publicvoidpaint(){
System.out.println("儿子用铅笔画好了一幅画。");
}
}
packagedecorator;
publicclassMotherimplementsWork{
//被装饰者
privateWorkwork;
publicMother(Workwork){
this.work=work;
}
privateMother(){}
publicvoidpaint(){
//妈妈装饰者做的职责
System.out.println("妈妈正在做给画上颜色前的准备工作。");
//被装饰者做的职责
work.paint();
//妈妈装饰者做的职责
System.out.println("妈妈给画上好了颜色。");
}
}
packagedecorator;
publicinterfaceWork{
publicvoidpaint();
}
publicinterfaceComponent
{
publicvoiddoSomething();
}
publicclassConcreteComponentimplementsComponent
{
@Override
publicvoiddoSomething()
{
System.out.println("功能A");
}
}
publicclassDecoratorimplementsComponent
{
privateComponentcomponent;
publicDecorator(Componentcomponent)
{
this.component=component;
}
@Override
publicvoiddoSomething()
{
component.doSomething();
}
}
publicclassConcreteDecorator1extendsDecorator
{
publicConcreteDecorator1(Componentcomponent)
{
super(component);
}
@Override
publicvoiddoSomething()
{
super.doSomething();
this.doAnotherThing();
}
privatevoiddoAnotherThing()
{
System.out.println("功能B");
}
}
publicclassConcreteDecorator2extendsDecorator
{
publicConcreteDecorator2(Componentcomponent)
{
super(component);
}
@Override
publicvoiddoSomething()
{
super.doSomething();
this.doAnotherThing();
}
privatevoiddoAnotherThing()
{
System.out.println("功能C");
}
}
publicclassClient
{
publicstaticvoidmain(String[]args)
{
Componentcomponent=newConcreteComponent();
Componentcomponent1=newConcreteDecorator1(component);
component1.doSomething();
System.out.println("-----------");
Componentcomponent2=newConcreteDecorator2(component1);
component2.doSomething();
}
}
• 2019/10/08 15:00
4
餐厅设计如何营造氛围5
金鱼池综合办公6
小型办公室应该如何装修?怎样做到又快又省钱