设计模式:装饰模式-decorator
2017-01-10 14:41
288 查看
动态地给一个对象添加一些额外的职责。就增加功能来说,decorator模式相比生成子类更加灵活
实际上就是decorator与concreteComponent是同一层次的可以替换的,在decorator中包含一个component对象,通过该对象调用原本的服务,并在该对象附近增加新服务
装饰模式的优点
(1)装饰模式与继承关系的目的都是要扩展对象的功能,但是装饰模式可以提供比继承更多的灵活性。装饰模式允许系统动态决定“贴上”一个需要的“装饰”,或者除掉一个不需要的“装饰”。继承关系则不同,继承关系是静态的,它在系统运行前就决定了。 (2)通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。
装饰模式的缺点
由于使用装饰模式,可以比使用继承关系需要较少数目的类。使用较少的类,当然使设计比较易于进行。但是,在另一方面,使用装饰模式会产生比使用继承关系更多的对象。更多的对象会使得查错变得困难,特别是这些对象看上去都很相像。
代码:
Mainpublic class Main { public static void main(String[] args) { Component component=new ConcreteComponent(); Component A=new ConcreteDecoratorA(component); A.sampleOperation(); Component B=new ConcreteDecoratorB(component); B.sampleOperation(); } }
interface:Component
public interface Component { public void sampleOperation(); }
imp:Decorator
public class Decorator implements Component { private Component componet; @Override public void sampleOperation() { this.componet.sampleOperation(); System.out.println("this is operation"); } public Decorator(Component component) { this.componet=component; } }
imp:ConcreteComponent
public class ConcreteComponent implements Component{ @Override public void sampleOperation() { System.out.println("sample operation"); } }
imp:ConcreteDecoratorA
public class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); } @Override public void sampleOperation() { super.sampleOperation(); System.out.println("concrete A"); } }
imp:ConcreteDecoratorB
public class ConcreteDecoratorB extends Decorator { public ConcreteDecoratorB(Component component) { super(component); } @Override public void sampleOperation() { super.sampleOperation(); System.out.println("concrete B"); } }
相关文章推荐
- 设计模式之装饰模式篇(Decorator)
- 设计模式之装饰模式篇(Decorator)
- NET设计模式之一:装饰模式(Decorator Pattern)
- 设计模式--装饰模式(Decorator)
- DOTA版设计模式——装饰模式[Decorator Pattern]
- 乐在其中设计模式(C#) - 装饰模式(Decorator Pattern)
- 设计模式[6] Decorator Pattern 装饰模式
- .NET设计模式(10):装饰模式(Decorator Pattern)
- .NET设计模式(10):装饰模式(Decorator Pattern)
- 设计模式c#语言描述——装饰(Decorator)模式
- 乐在其中设计模式(C#) - 装饰模式(Decorator Pattern)
- 设计模式c#描述——装饰(Decorator)模式
- 乐在其中设计模式(C#) - 装饰模式(Decorator Pattern)
- 我读设计模式之装饰模式(Decorator Pattern)
- 设计模式c#语言描述——装饰(Decorator)模式
- 结构型设计模式---Decorator模式(装饰模式)
- 解读设计模式----装饰模式(Decorator Pattern)
- [导入]C#面向对象设计模式纵横谈(10):Decorator 装饰模式(结构型模式).zip(9.84 MB)
- .NET设计模式(10):装饰模式(Decorator Pattern)
- 设计模式(11)-装饰模式(Decorator)