装饰模式
装饰模式
1.模式动机
一般有两种方式可以实现给一个类或对象增加行为:
继承机制,使用继承机制是给现有类添加功能的一种有效途径,通过继承一个现有类可以使得子类在拥有自身方法的同时还拥有父类的方法。但是这种方法是静态的,用户不能控制增加行为的方式和时机。
关联机制,即将一个类的对象嵌入另一个对象中,由另一个对象来决定是否调用嵌入对象的行为以便扩展自己的行为,我们称这个嵌入的对象为装饰器(Decorator)。
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任,换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不需要创造更多子类的情况下,将对象的功能加以扩展。这就是装饰模式的模式动机。
2.模式定义
装饰模式(Decorator Pattern) :动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。其别名也可以称为包装器(Wrapper),与适配器模式的别名相同,但它们适用于不同的场合。根据翻译的不同,装饰模式也有人称之为“油漆工模式”,它是一种对象结构型模式。
3.模式结构
装饰模式包含如下角色:
Component: 抽象构件
ConcreteComponent: 具体构件
Decorator: 抽象装饰类
ConcreteDecorator: 具体装饰类
4.模式分析
与继承关系相比,关联关系的主要优势在于不会破坏类的封装性,而且继承是一种耦合度较大的静态关系,无法在程序运行时动态扩展。在软件开发阶段,关联关系虽然不会比继承关系减少编码量,但是到了软件维护阶段,由于关联关系使系统具有较好的松耦合性,因此使得系统更加容易维护。当然,关联关系的缺点是比继承关系要创建更多的对象。使用装饰模式来实现扩展比继承更加灵活,它以对客户透明的方式动态地给一个对象附加更多的责任。装饰模式可以在不需要创造更多子类的情况下,将对象的功能加以扩展。
典型的抽象装饰类代码:
public class Decorator extends Component
{
private Component component;
public Decorator(Component component)
{
this.component=component;
}
public void operation()
{
component.operation();
}
}
典型的具体装饰类代码:
public class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component)
{
super(component);
}
public void operation()
{
super.operation();
addedBehavior();
}
public void addedBehavior()
{
//新增方法
}
}
5.装饰模式实例与解析
实例一:
变形金刚变形金刚在变形之前是一辆汽车,它可以在陆地上移动。当它变成机器人之后除了能够在陆地上移动之外,还可以说话;如果需要,它还可以变成飞机,除了在陆地上移动还可以在天空中飞翔。
UML类图:
代码实现:
//Transform接口
package priv.qzz.DesignPattern.DecoratorPattern_13;
public interface Transform
{
public void move();
}
//Changer类
package priv.qzz.DesignPattern.DecoratorPattern_13;
public class Changer implements Transform
{
private Transform transform;
public Changer(Transform transform)
{
this.transform=transform;
}
public void move()
{
transform.move();
}
}
//Airplane类
package priv.qzz.DesignPattern.DecoratorPattern_13;
public class Airplane extends Changer
{
public Airplane(Transform transform)
{
super(transform);
System.out.println("变成飞机!");
}
public void fly()
{
System.out.println("在天空飞翔!");
}
}
//Car类
package priv.qzz.DesignPattern.DecoratorPattern_13;
public final class Car implements Transform
{
public Car()
{
System.out.println("变形金刚是一辆车!");
}
public void move()
{
System.out.println("在陆地上移动!");
}
}
//Robot类
package priv.qzz.DesignPattern.DecoratorPattern_13;
public class Robot extends Changer
{
public Robot(Transform transform)
{
super(transform);
System.out.println("变成机器人!");
}
public void say()
{
System.out.println("说话!");
}
}
//Client类(含有main方法)
package priv.qzz.DesignPattern.DecoratorPattern_13;
public class Client
{
public static void main(String args[])
{
Transform camaro;
camaro=new Car();
camaro.move();
System.out.println("-----------------------------");
Airplane bumblebee=new Airplane(camaro);
bumblebee.move();
bumblebee.fly();
}
}
结果:
变形金刚是一辆车!
在陆地上移动!
-----------------------------
变成飞机!
在陆地上移动!
在天空飞翔!
2019.3.23/周六
by 922